I have written a play to
- Generate pub keys on the host1
- Copy the pub keys on my control machine
- Deploy the pub keys on a second host, i.e. host2
- hosts: '{{ target }}'
tasks:
- name: Check admin pub keys are present on host1
stat:
path: /var/services/homes/admin/.ssh/id_rsa.pub
- name: Generate pub keys on host1 if non-existing
user:
name: admin
generate_ssh_key: yes
ssh_key_bits: 4096
when: stat_result.stat.exists == False
- name: Downloading pub key from host1 to the control machine
command: scp admin@{{ansible_host}}:/var/services/homes/admin/.ssh/id_rsa.pub /tmp/
delegate_to: 127.0.0.1
- name: Copy pub key of host1 to host2
authorized_keys:
user: admin
key: "{{ lookup('file', '/tmp/id_rsa.pub') }}"
state: present
I run it with:
ansible-playbook -i hosts keys.yml -e "target=host1"
The problem is in the last task, i.e. Copy pub key of host1 to host2. The way it is written it will copy the pub key again to host1.
How can I tell Ansible to copy the pub key to host2 instead? Thanks
Two options. On host1:
If
ssh-copy-id
is available:or
Note: I haven't tested. You may want to tweak it to make it work.