在Ansible中创build非root用户并禁用根SSH

我试图编写一个Ansible手册来引导我的服务器。 默认情况下,我只能使用root用户名和密码login,所以我的playbook以root身份login,使用SSH密钥创build非root用户,并禁用root和SSH密码。

这是一个问题,因为我现在不能再次运行该剧本,因为根login被禁用! 我希望剧本是幂等的,不必在引导它们之后添加和删除主机。

如果使用linode模块在Linode上创build服务器,则可以注册linode任务的return value ,并将检查超出linode任务的条件包含在引导任务中。 这应该是幂等的。 尝试这样的事情:

 - linode: api_key: 'longStringFromLinodeApi' name: linode-test1 plan: 1 datacenter: 2 distribution: 99 password: 'superSecureRootPassword' private_ip: yes ssh_pub_key: 'ssh-rsa qwerty' swap: 768 wait: yes wait_timeout: 600 state: present register: linode_node - include: bootstrap.yml when: linode_node.changed 

bootstrap.yml将包含禁用ssh rootlogin等所需的所有任务。

我会做以下几点:

  • 创build一个angular色(像“基地”),你(除其他外),创造一个合适的用户(和sudo规则),以便使用
  • 创build或调整您的SSHangular色,pipe理sshd_config (我倾向于build议您使用templatepipe理整个文件,但这取决于您),并禁用rootlogin
  • 让你的SSHangular色依赖于基础angular色,例如使用元。

对于第一个angular色(基础angular色),我倾向于使用类似于:

  name: base | local ansible user | create user user: name: "{{ local_ansible_user }}" group: "{{ local_ansible_group }}" home: "/home/{{ local_ansible_user }}" state: present generate_ssh_key: "{{ local_ansible_generate_key }}" ssh_key_bits: 4096 ssh_key_type: rsa tags: - ansible - local_user - name: base | local ansible user | provision authorised keys authorized_key: user: "{{ local_ansible_user }}" state: present key: "{{ item }}" with_items: "{{ local_ansible_authorised_keys }}" tags: - ansible - authorised_keys 

对于SSHconfiguration,我会使用:

 - name: openssh | server | create configuration template: src: sshd_config.j2 dest: /etc/ssh/sshd_config owner: root group: root mode: "0640" validate: "/usr/sbin/sshd -tf %s" notify: - openssh | server | restart tags: - ssh - openssh 

这里logging了 Ansible的angular色依赖关系。

你也可以在你的剧本中使用sorting来做到这一点。

如果你想在上下文中看到,我在github上有一些可靠的东西 (从上面得到的)

也许你可以在引导主机后修改清单中的ansible_ssh_user

 [targets] other1.example.com ansible_connection=ssh ansible_ssh_user=root # new host other2.example.com ansible_connection=ssh ansible_ssh_user=user # bootstrapped host 

我喜欢这样做:

 - hosts: all remote_user: root gather_facts: no tasks: - name: Check ansible user command: ssh -q -o BatchMode=yes -o ConnectTimeout=3 ansible@{{ inventory_hostname }} "echo OK" delegate_to: 127.0.0.1 changed_when: false failed_when: false register: check_ansible_user - block: - name: Create Ansible user user: name: ansible comment: "Ansible user" password: $6$u3GdHI6FzXL01U9q$LENkJYHcA/NbnXAoJ1jzj.n3a7X6W35rj2TU1kSx4cDtgOEV9S6UboZ4BQ414UDjVvpaQhTt8sXVtkPvOuNt.0 shell: /bin/bash - name: Add authorized key authorized_key: user: ansible key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" exclusive: yes - name: Allow sudo for ansible copy: content: ansible ALL=(ALL) ALL dest: /etc/sudoers.d/ansible mode: 0600 when: check_ansible_user | failed 

我尝试用我的用户连接到远程主机。 如果这是不可能的(在第一次运行),我作为根连接,并创build一个合法的用户连同其authorized_keys文件和sudo权限。

在随后的运行中,作为有用的用户进行连接,所以可以跳过任务块。

一旦远程主机被引导,我可以继续与这个合适的用户一起become

 - hosts: all remote_user: ansible become: yes roles: - ...