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 a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

Building a Production - Ready Node....

In this article, we will see how to build a Nodejs, TypeScript Application and d...

Nginx for Front-end Developers

This article is to explain Nginx for Front-end Developers in a much simpler way....

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...