Search code examples
ansibleauthorized-keys

Ansible: Append key content of host1 to authorized_keys of host2


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


Solution

  • 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.