11

I wonder how to copy my SSH public key to many hosts using Ansible.

First attempt:

ansible all -i inventory -m local_action -a "ssh-copy-id {{ inventory_hostname }}" --ask-pass

But I have the error The module local_action was not found in configured module paths.

Second attempt using a playbook:

- hosts: all
  become: no
  tasks:
  - local_action: command ssh-copy-id {{ inventory_hostname }}

Finally I have entered my password for each managed host:

ansible all -i inventory --list-hosts | while read h ; do ssh-copy-id "$h" ; done

How to fill password only once while deploying public SSH key to many hosts?



EDIT:   I have succeeded to copy my SSH public key to multiple remote hosts using the following playbook from the Konstantin Suvorov's answer.

- hosts: all
  tasks:
  - authorized_key:
      key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"

The field user should be mandatory according to the documentation but it seems to work without. Therefore the above generic playbook may be used for any user when used with this command line:

ansible-playbook -i inventory authorized_key.yml -u "$USER" -k
oHo
  • 51,447
  • 27
  • 165
  • 200
  • For me, the `user` variable was required. I have set it to `"{{ ansible_user_id }}"` to use the current user name, but it can be set to something else if desired. – nwinkler Sep 13 '18 at 09:42
  • FAILED! => {"changed": false, "msg": "missing required arguments: user"} – DimiDak Jan 28 '19 at 11:38

1 Answers1

14

Why don't you use authorized_key module?

- hosts: all
  tasks:
    - authorized_key:
        user: remote_user_name
        state: present
        key: "{{ lookup('file', '/local/path/.ssh/id_rsa.pub') }}"

and run playbook with -u remote_user_name -k

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • 1
    password? Supposingly this is the first time the Ansible master connects to the new remote hosts. Otherwise why not ssh-id-copy – DimiDak Jan 28 '19 at 11:41