Can You Use Ansible To Dynamically Load The Respective OS’s package in The Same Playbook?

Let us take an example where we need to configure a server (let’s say a web server) on top of an OS. For such use cases, we can use Ansible, which is one of the most popular and widely used configuration management tools.

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.

Basically, the main aim of this task is to:

🔰 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. ( No need to use when keyword here.)

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:

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.

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.

See you in the next blog.

I am an active learner who likes to challenge every problem with a can-do mindset in order to make any idea a reality.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store