qbi
qbi

Reputation: 2144

Distributing different SSH keys to different hosts in one inventory

I have an inventory which contains several hosts. I want to distribute the public part of the SSH keys via Ansible. Each host gets an own key. So far I found the module authorized_keys which can do the general job. However I was not able to figure out how can distribute the different keys.

My .ssh directory is like:

ls .ssh
hostA hostA.pub
hostB hostB.pub
hostC hostC.pub

For one host I could write:

- name: Set authorized key taken from file
  authorized_key:
    user: joeuser
    state: present
    key: "{{ lookup('file', '/home/joeuser/.ssh/hostA.pub') }}"

But how can I do this for different hosts?

Upvotes: 0

Views: 75

Answers (1)

larsks
larsks

Reputation: 312650

If each key is named after the hostname, as is suggested by your question, you could just do:

- name: Set authorized key taken from file
  authorized_key:
    user: joeuser
    state: present
    key: "{{ lookup('file', '/home/joeuser/.ssh/{}.pub'.format(inventory_hostname)) }}"

Upvotes: 1

Related Questions