Quick tip: Add multiple users with multiple public SSH keys with Ansible

Because it took me a while to figure out how to do it cleanly, here’s my solution for adding multiple users with multiple public SSH keys on a server, using Ansible:

in login-vars.yml

users:
- login: "user1"
  pass_hash: "$6$G1Q........"
  pubkeys: 
    - "ssh-rsa AAAAB3N.....yBd1 user1@first-key"
    - "ssh-rsa AAAAB3N.....eWDp user1@second-key"
- login: "user2"
  pass_hash: "$6$G1A........"
  pubkeys: 
    - "ssh-rsa AAAAB3N.....yCDd1 user2@first-key"
    - "ssh-rsa AAAAB3N.....eaop user2@second-key"

in roles/setup-users/main.yml

- name: configure user accounts
  user:
    name={{ item.login }} 
    append=yes
    password={{ item.pass_hash }}
  become: yes
  with_items:
    - "{{ shell_users }}"

- name: Add users public keys
  authorized_key:
    user={{ item.login }}
    key="{% for key in item.pubkeys %}{{ key ~ "\n" }}{% endfor %}"
  become: yes
  with_items:
    - "{{ shell_users }}"