Ansible – Creating User and SSH Key with Ansible User Module

ansible-playbook

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.

Best 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 zahr1@localhost"

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 zahr1@localhost"
    - "ssh-rsa AAAAA.....2 zahr1@localhost"
    - "ssh-dsa AAAAA.....3 zahr1@localhost"

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.

Related Topic