Can Ansible deploy public SSH key asking password only once?

oHo picture oHo · Jun 22, 2017 · Viewed 9.5k times · Source

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

Answer

Konstantin Suvorov picture Konstantin Suvorov · Jun 22, 2017

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