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
4
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.

1vars_files:
2 - config.yml

config.yml

Below are the contents of config.yml.

1---
2id_rsa_file: "/root/.ssh/id_rsa"
3passphrase: "changeit"
4root_password: "password"
5nodes:
6 - 1.2.3.4
7 - 5.6.7.8
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.

To Read More

Everything you need to know about d...

Docker volume is a persistent data storage mechanism to store the data in docker...

How to remove docker image - Docker...

This guide will cover everything you need to know about removing docker images f...

How to build an Actionable data ta...

In this article, we will see how to build an Actionable data table using a react...