使用playbook中的authorized_key模块为新用户设置SSH密钥

时间:2016-04-19 15:20:17

标签: python ssh ansible ansible-playbook authorized-keys

情景:

根据hosts文件的[clients]部分执行以下操作:

  1. 检查用户“foo”的SSH登录是否失败,如果是
  2. 使用authorized_key模块
  3. 为用户“foo”添加SSH密钥
  4. 假设用户“foo”已存在于远程计算机上,并且已在本地(ansible)主机上创建了SSH公钥
  5. 我知道this solution使用Ansible命令行,但我希望能够将它放入剧本中。使用密码(包括sudo)输入脚本是可以接受的。

    现在我想出了如何使用第三方角色GROG.authorized-key做我想做的事情,但它仍然要求我用-K开关运行playbook。 Ansible中是否存在某些内容(在命令行开关旁边),只有在需要时才会提示输入密码?

    - hosts: clients
      vars:
        authorized_key_list:
          - name: pdo
            authorized_keys:
             - key: "{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"
               state: present
      roles:
        - { role: GROG.authorized-key }
    

2 个答案:

答案 0 :(得分:1)

我认为根据你的意见,这应该有效:

- hosts: clients
  become: true
  tasks: 
  - name: Add authorized_key to pdo user on the remote client machine(s)
    authorized_key: user=foo key="{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"

使用-K调用它以获取成为密码的问题。这将在远程计算机上生成sudo命令。多数民众赞成你需要的,不是吗?

答案 1 :(得分:0)

GROG帮助我理解我做错了什么的特别赞誉。

基本上我在以非root用户身份运行Ansible playbook时尝试root作业。我最终创建了以下bootstrap.yml并使用此命令运行它:

ansible-playbook ./bootstrap.yml -u root -k

这将以root密码提示符以root身份运行我的playbook,并且能够创建用户并建立sudo和无密码访问

---
# file: bootstrap.yml
# Execute once as root user to create a public key and install it to your client machine(s) using the following command
# ansible-playbook ./auth-client.yml -u root -k

# This requires you to install GROG.management-user role from the Ansible Galaxy using this command:
# ansible-galaxy install GROG.management-user

# Add pdo user on remote machines
- hosts: all
  tasks:
  - name: Add remote users
    user: name=pdo group=users

# Generate SSK keys at the localhost for pde user
- hosts: localhost
  tasks:
  - name: Provision local pdo user
    user: name=pdo generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa

# Install public key into remote machine    
- hosts: all
  vars:
    authorized_key_list:
      - name: pdo
        authorized_keys:
         - key: "{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"
           state: present
  roles:
    - { role: GROG.authorized-key }

# Add sudo privileges for pdo user
- hosts: all
  roles:
  - { role: GROG.sudo, become: yes }