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

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

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

What is gRPC ? How to implement gRP...

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