creating user and sshkey with ansible user module

Solution 1:

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.

Solution 2:

Ansible authorized_key seems to not use the become_user, so does not have access to the .ssh folder of the user. Solution: copy the <user>/.ssh/id_rsa.pub file to a /tmp location (as root/become_user) and then use authorized_keys to lookup in the /tmp folder. Below adhoc commands to do the job. In a playboook add a task with the copy module. (first export PASS=mysecret unless you want to replace the -e extra parameter with -k and type 5 times the password)

create the new user first on the ansible control host and generate new ssh keys

ansible localhost -m user -a "name=${a_new_user} generate_ssh_key=true"  \
-b -e "ansible_become_pass=${PASS}"

create this user also on all the hosts

ansible all -m user -a "name=${a_new_user}" -b -e  \
"ansible_become_pass=${PASS}"

copy the just created public key to a location that is accessable by the authorized_key command

sudo cp -p /home/${a_new_user}/.ssh/id_rsa.pub /tmp/

now authorized_key can add the public key on all the hosts in the authorized_key file , but now lookup in the /tmp folder

ansible all -m authorized_key -a "user=${a_new_user} \
key={{ lookup('file', '/tmp/id_rsa.pub') }}" -b \
-e "ansible_user_passwd=${PASS}"

make sure the newly added user can sudo without password

ansible all -m lineinfile -a "path=/etc/sudoers state=present \
line='${a_new_user} ALL=(ALL) NOPASSWD: ALL' \
validate='/usr/sbin/visudo -cf %s'" -b \
-e "ansible_become_pass=${PASS}"