Load variable files Dynamically with respect to the OS using Ansible

Problem Statement:

Create an Ansible Playbook which will dynamically load the variable file named the same as OS name and just by using the variable names we can Configure our target node.
(Note: No need to use when keyword here.)


Now, the thing is that we may have multiple Operating Systems. We can definitely use Ansible to configure all of them at a time. But, the package/software name may vary from OS to OS.

And here, we might have to create multiple tasks for all the Operating Systems, which is not an efficient setup.

Here, we want some kind of intelligence that just by looking at the OS name and version, the Ansible should automatically decide which package needs to be installed.

For example, if the OS is RedHat, the package for the webserver would be ‘httpd’. The same for Ubuntu would be ‘apache2’. And here, Ansible should dynamically check the OS name and version and install the respective package.

Let’s say I am going to use two OS for the same, one is RedHat8.3 and the other is Ubuntu20.04. I am going to create two variable files in the format- [OSname]:[Version].

I have created the above variable files:

I am launching both the OS on the AWS cloud, you can launch them locally as well.

Now, let’s create a playbook for the same:

Here, all we need to do is to just change the host where this playbook is going to run. And then, using the Ansible Facts, it will automatically find out the OS details and import the variable file accordingly.

To run the playbook, this is the configuration file and inventory of Ansible:

Next step is to run the playbook, so let’s run the playbook for ‘Redhat’:

Next step is to run the playbook for ‘Ubuntu’:

And as we can see, the playbook ran successfully on both the OS by loading the respective package dynamically.

That was all. I hope you liked the blog.



Categories: DevOps

Tags: , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: