Ansible - Password-less SSH Playbook
Ansible - Password-less SSH Playbook
In the blog Enable SSH Communication we saw how to establish SSH communication between ansible control machine and the nodes.
There we did generate a SSH key pair and copied the public key to nodes. All these tasks had to be done manually. Now we’ll see a way to automate that too using a playbook.
Check for id_rsa file and create if not exist
Below task can be used to check if the id_rsa file already present in the control machine. If its there playbook will use the same key file else create a new key pair.
- stat:
path: "{{ id_rsa_file }}"
register: op
- name: Generating ssh key pair
command: ssh-keygen -t rsa -b 4096 -f "{{ id_rsa_file }}" -q -N "{{ passphrase }}"
when: op.stat.exists == false
Copy rsa public key to nodes
Below task copies the rsa public key to all the nodes.
- name: Copy public key to the nodes
command: sshpass -p "{{ root_password }}" ssh-copy-id -i "{{ id_rsa_file }}" root@"{{ item }}" -f -o StrictHostKeyChecking=no
with_items:
- "{{ nodes }}"
Here you can see, we have used with_items to loop. So this task copies the key to multiple nodes in a loop. And we will call a config.yml file where we have declared our variables.
vars_files:
- config.yml
config.yml
Below are the contents of config.yml.
---
id_rsa_file: "/root/.ssh/id_rsa"
passphrase: "changeit"
root_password: "password"
nodes:
- 1.2.3.4
- 5.6.7.8
- 9.10.11.12
Here as you see, we can add multiple servers under nodes. root_password will be the password which will be used to login to the nodes for copying the ssh public key.
Full playbook can be found in this git repo ansible-password-less-ssh.