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