Use Passwordless SSH Keys with Ansible to Manage Machine

In this blog, Post I will show you how to stop using sudo password to manage Linux machines with Ansible.

By default, when you run an Ansible command \ playbook against Linux machines, you need to use the -b and -K switches.

The two switches will run the command as sudo and ask for a password.

The above is OK in small deployment. However, it is hard to scale this way or manage a large number of machines.

The Solution

We can bypass this problem by using two things:

  • Private \ Public SSH – We create a public and private key and copy the public key to hosts machines while keeping the private key on the control node.
  • We add the service account user on the node to the sudoers file – This will allow us to run the playbook with a service account without using sudo.

Create Private and Public Key

On the Ansible control node, I will create an SSH using the following command.

ssh-keygen -t rsa -C "email@address.local"

Note down the locations of the files, and do not use a passphrase.

The output will look like this:

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.

Run the following two commands.

ssh-agent bash

$ ssh-add ~/.ssh/id_rsa

Copy SSH files

Next, I will copy the public SSH key to my host machine, which I would like to manage with Ansible.

The IP address of my machine is: 172.16.16.0

ssh-copy-id -i ~/.ssh/id_rsa.pub admin@172.16.0.6

SSH to Host

I will connect to my host using SSH

ssh admin@172.16.0.6

If I copied the file correctly, I would not be asked for a password.

Edit Sudoers

From the host machine, I will open the following file.

nano /etc/sudoers

At the bottom of the file, I will add the following line.

admin ALL=(ALL) NOPASSWD:ALL

Run Playbook

Now, I can run a playbook without using -b and -k.

ansible-playbook -i hosts  playbook01.yaml

Processing…
Success! You're on the list.

Posted

in

by