Ssh – Ansible deploy multiple authorized_keys on multiple hosts

ansiblesshssh-keys

We need deploy keys on the servers, but trick is that the keys are many and do not all of them must have deploy on all servers. Now we do it follows:

in vars roles/authorized_keys/vars/main.yml

ssh_users:
  - name: bob
    key: "{{ lookup('file', 'roles/authorized_keys/vars/bob.pub') }}" 
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/user.pub') }}"
    state: absent

in task: roles/authorized_keys/tasks/main.yml

- name: Add ssh key.
    authorized_key: user={{ item.name }} key="{{ item.key }}" state={{ item.state }}
    with_items: ssh_users

in playbook: authorized_keys.yml

---
- hosts: '{{ hosts }}'
  vars_files:
    - '{{ vars }}'
  roles:
    - { role: authorized_keys }

Before start playbook change roles/authorized_keys/vars/main.yml (present or absent).
When start playbook add hosts and hosts group:

ansible-playbook -i production --extra-vars "hosts=web:pg:1.2.3.4" authorized_keys.yml

Previously, it was all good, but now increased the number of keys and servers. And now I do not remember whose key is to be on what server.

Tell me please how I can set up the list of hosts for each key?
For example something like this:

- name: bob
    key: "{{ lookup('file', 'roles/authorized_keys/vars/bob.pub') }}" 
    servers: web,database,12.12.12.12
    state: present
- name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    servers: api,pg,30.30.30.30
    state: present

Best Answer

I would use a host variable "ssh_users", which states the users that need their host keys added.

- ssh_users:
   - bob
   - root
   - alice

Then, you have a seperate variable file that defines the name, key and state for each SSH user. Import that variable file, then call your original task pretty much as is.