ansible - 将密钥复制到授权密钥文件

时间:2017-09-14 15:53:40

标签: ansible

我创建了一个使用ansible的用户,现在想将.ssh / id_rsa.pub文件复制到authorized_keys文件。

我检查了authorized_keys模块,但是用于将密钥从主机复制到访客。

想知道正确的做法是什么。

- name: Adding user  - {{ user }}  
  user: name={{ user }}
        group={{ group }}
        shell=/bin/bash
        password=${password}
        groups=sudo
        append=yes
        generate_ssh_key=yes
        ssh_key_bits=2048
        ssh_key_file=.ssh/id_rsa

1 个答案:

答案 0 :(得分:2)

user模块返回生成的密钥,因此您可以register结果,然后在后续authorized_key任务中使用密钥。也就是说,如果我有这样的剧本:

- hosts: localhost
  tasks:
    - name: add user
      user:
        name: testuser
        shell: /bin/bash
        password: secret
        append: yes
        generate_ssh_key: yes
        ssh_key_bits: 2048
      register: newuser

    - debug:
        var: newuser

我会看到输出类似于:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "newuser": {
        "append": true, 
        "changed": true, 
        "comment": "", 
        "group": 21946, 
        "home": "/home/testuser", 
        "move_home": false, 
        "name": "testuser", 
        "password": "NOT_LOGGING_PASSWORD", 
        "shell": "/bin/bash", 
        "ssh_fingerprint": "2048 SHA256:Tn6UOl/WYToJCaW3QUnLMWgEfthILIsoCP+534qWzfw ansible-generated on lkellogg-pc0dzzve (RSA)", 
        "ssh_key_file": "/home/testuser/.ssh/id_rsa", 
        "ssh_public_key": "ssh-rsa ... ansible-generated on examplehost", 
        "state": "present", 
        "uid": 21940
    }
}

所以你可以添加这样的任务:

- authorized_key:
    user: root
    state: present
    key: "{{ newuser.ssh_public_key }}"