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.

1- stat:
2 path: "{{ id_rsa_file }}"
3 register: op
5 - name: Generating ssh key pair
6 command: ssh-keygen -t rsa -b 4096 -f "{{ id_rsa_file }}" -q -N "{{ passphrase }}"
7 when: op.stat.exists == false

Copy rsa public key to nodes

Below task copies the rsa public key to all the nodes.

1- name: Copy public key to the nodes
2 command: sshpass -p "{{ root_password }}" ssh-copy-id -i "{{ id_rsa_file }}" root@"{{ item }}" -f -o StrictHostKeyChecking=no
3 with_items:
4 - "{{ 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.

2 - config.yml


Below are the contents of config.yml.

2id_rsa_file: "/root/.ssh/id_rsa"
3passphrase: "changeit"
4root_password: "password"
6 -
7 -
8 -

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.

To Read More

Building Nodejs Microservice - A Cl...

This Article explains everything about how to build Nodejs Microservices in clou...

I Accidentally wiped the entire dat...

One of the tragic accident in my job turned out to be good learning for me in re...

List of Docker Container Commands y...

This article covers list of commands that you should know to manage docker conta...