1
votes

Ansible use ssh to setup softwares to remote hosts.

If there are some fresh machines just been installed, run Ansible playbook from one host will not connect them because of no authorized_keys on remote hosts.

If copy the Ansible host's pub key to those target hosts like:

$ ssh user@server "echo \"`cat .ssh/id_rsa.pub`\" >> .ssh/authorized_keys"

First should ssh login and make file on every remote host:

$ mkdir .ssh
$ touch .ssh/authorized_keys

Is this the common way to run Ansible playbook to remote servers? Is there a better way exist?

1

1 Answers

3
votes

I think it's better to do that using Ansible as well, with the authorized_key module. For example, to authorize your key for user root:

ansible <hosts> -m authorized_key -a "user=root state=present key=\"$(cat ~/.ssh/id_rsa.pub)\"" --ask-pass

This can be done in a playbook also, with the target user as a variable that defaults to root:

- hosts: <NEW_HOSTS>
  vars:
  - username: root    

  tasks:
  - name: Add authorized key
    authorized_key: 
      user: "{{ username }}"
      state: present
      key: "{{ lookup('file', '/home/<YOUR_USER>/.ssh/id_rsa.pub') }}"

And executed with:

ansible-playbook auth.yml --ask-pass -e username=<TARGET_USER>

Your user should have privileges, if not use became.