creating user and sshkey with ansible user module

Alireza Nasri asked:

I wanna create some local and remote users and generate ssh keypair for respective users and transfer them to remote server but it seems local user – ansible – which runs ansible-playbook does not have access to /home/USERNAME/.ssh/id_rsa.pub

TASK [copy ssh key to destination users] ***************************************************************************************************
task path: /home/ansible/project1/setup-user.yaml:21
Read vars_file 'vars/users.yaml'
Read vars_file 'vars/groups.yaml'
[WARNING]: Unable to find '/home/zahr1/.ssh/id_rsa.pub' in expected paths (use -vvvvv to see paths)
File lookup using None as file
fatal: [localhost]: FAILED! => {
    "msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /home/zahr1/.ssh/id_rsa.pub"
}
[WARNING]: Unable to find '/home/zahr1/.ssh/id_rsa.pub' in expected paths (use -vvvvv to see paths)
File lookup using None as file
fatal: [ansible1]: FAILED! => {
    "msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /home/zahr1/.ssh/id_rsa.pub"
}

I’d appreciate if you let me know the solution.

My answer:


You can copy the public key directly into your playbook. For example:

- name: Set authorized key
  ansible.posix.authorized_key:
    user: zahr1
    state: present
    key: "ssh-ed25519 AAAAA.....0 [email protected]"

You can also specify multiple keys.

- name: Set authorized key
  ansible.posix.authorized_key:
    user: zahr1
    state: present
    key: "{{ item }}"
  loop:
    - "ssh-ed25519 AAAAA.....1 [email protected]"
    - "ssh-rsa AAAAA.....2 [email protected]"
    - "ssh-dsa AAAAA.....3 [email protected]"

Note that ansible.posix.authorized_key is for Ansible 2.10 and later (see its documentation as it must be installed separately with ansible-galaxy). Older versions of Ansible will use the now-deprecated authorized_key.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.