Ansible – In and Out | Refactoring Inventory | Part 6

As of now we are keeping our password in the inventory file, which is not at all a good practice. Let’s remove our passwords from there and login via key based login which is the ideal approach.

ssh-keygen

This command will generate a key and by default will place the key at location

ls ~/.ssh/

authorized_keys  id_rsa  id_rsa.pub  known_hosts

Let’s copy this key to the target machines

ssh-copy-id [email protected]

We will be doing this operation for all the machines. This is a one time effort, it will make our machines more secure. By default while doing an ssh our machine will try to pick configurations for key based login, if not found then move to the password authentication method. We can remove password authentication from the target machines.

Remove password from the inventory file

Now our updated inventory file will look like below.

websrv01 ansible_host=172.31.34.188
websrv02 ansible_host=172.31.1.113
websrv03 ansible_host=172.31.30.170
dbsrv01 ansible_host=172.31.28.57


#creating group
[websrvgrp]
websrv01
websrv02
websrv03


[dbsrvgrp]
dbsrv01


#creating groups of groups
[DC_NCALI:children]
websrvgrp
dbsrvgrp

[DC_NCALI:vars]
ansible_user=devops

That’s how we can convert the password-based authentication to the key based authentication which is a more secure way of connecting to the target machines.

Similarly we can remove our username as well and place it in ansible.cfg file with variable remote_user.

Remove host IP addresses from inventory file

Its time to get rid of the IP’s written in the inventory file. We will be placing the IP’s in /etc/hosts file. Our hosts file and inventory file now will look somewhat like this:

Let’s test this now

ansible -m ping all

Using Ansible SSH private key variable

We have seen that the private and public key by default get stored in the user’s home directory. But what if we have stored the keys in a different path or if the private key to log in to the target machines are different for different machines? 

So, in all those cases we can make use of a very significant variable named “ansible_ssh_private_key_file”. 

Thus, we are going to update our inventory file with the path of our private key, though we have the same private key to log in for all the target machines. Updated inventory file will be like.

websrv01
websrv02
websrv03
dbsrv01


#creating group
[websrvgrp]
websrv01
websrv02
websrv03


[dbsrvgrp]
dbsrv01


#creating groups of groups
[DC_NCALI:children]
websrvgrp
dbsrvgrp

[DC_NCALI:vars]
ansible_user=devops
ansible_ssh_private_key_file = /home/ubuntu / .ssh / id_rsa

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts