Create and distribute ssh-keys using ansible

90 Views Asked by At

Using an ansible playbook, I need to create a ssh-key with the name 'mykey' for each host in the group 'client'.

After that I need to add this generated ssh-key (the public key, of course) to the one authorized_keys file of one user of one host 'server'.

I know how to generate ssh-keys with ansible, and I know how to add one to the authorized_keys file, but I do not know to add keys of many clients to the authorized_keys file of one server. Any ideas? TIA!

1

There are 1 best solutions below

0
t777 On BEST ANSWER

I found a solution, using the register and delegate_to options.

Here is a snippet of my playbook:

- hosts:
    - myclients

  - name: Create ssh-client-keypair for each client
    openssh_keypair:
      path: /root/.ssh/myid
      comment: {{ inventory_hostname }}
      type: ed25519
      state: present
    register: generated_key

  - name: Add ssh-public-key to (single) server
    ansible.posix.authorized_key:
      user: root
      key: "{{ generated_key.public_key }}"
      comment: "{{ generated_key.comment }}"
      state: present
    delegate_to: myserver