Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Ansible deploy public SSH key asking password only once?

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
like image 322
oHo Avatar asked Jun 22 '17 19:06

oHo


Video Answer


1 Answers

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

like image 51
Konstantin Suvorov Avatar answered Sep 18 '22 23:09

Konstantin Suvorov