Ansible: Append key content of host1 to authorized_keys of host2

1.4k views Asked by At

I have written a play to

  1. Generate pub keys on the host1
  2. Copy the pub keys on my control machine
  3. 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

3

There are 3 answers

0
helloV On BEST ANSWER

Two options. On host1:

If ssh-copy-id is available:

shell: ssh-copy-id admin@host2

or

shell: cat /var/services/homes/admin/.ssh/id_rsa.pub | (ssh admin@host2 "cat >> ~/.ssh/authorized_keys")

Note: I haven't tested. You may want to tweak it to make it work.

2
Ben Coughlan On

I think this might be your scp command.

It's a tricky one alright, but can't you just scp the keys straight to host2? you would be using passwords to get there anyway no?

i.e.

scp admin@host1:/var/services/homes/admin/.ssh/id_rsa.pub admin@host2:/usr/admin/.ssh/.

Is there a further reason why you need to use the "control host"? i.e. is the ansible script running from there?

edits:

 scp admin@host1:/var/services/homes/admin/.ssh/id_rsa.pub admin@host2:/tmp/.

cat /tmp/id_rsa.pub >> /usr/admin/.ssh/authorized_keys
0
Pauster On

With all my respect, I don't think that the answer of "helloV" is correct, due to the playbook, it would copy the public key from host1 to authorized_keys of host2, but also it will attempt to copy the public key from host2 to auhorized_keys on host2. And if the public key doesn't exist in host2 if will fail. If you want this to work only in the case from host1 to host2 you should use a when statement, but also, I don't think it is the right way to do it, maybe you should include public key in the playbook as a file an then you can use when you want. So my proposal would be the next:

- name: Copy public key to authorized keys
  shell: cat /var/services/homes/admin/.ssh/id_rsa.pub | (ssh admin@host2 "cat >> ~/.ssh/authorized_keys")
  when: target == "host1" 

host1 should be changed with the host1 name gived in {{target}}