Create an Ansible Playbook which will dynamically load the variable file named same as OS_name and just by
using the variable names we can Configure our target node.

Pratyush Pathak
3 min readMar 28, 2021

(Note: No need to use when keyword here.)

Let’s start!

To perform this task, first we will have to configure the ansible inventory file and ansible.cfg file

vim /etc/ansible/ansible.cfg

And then we will have to update the IP address and the credentials

vim /root/ip.txt

Here you can see:

Now we can list the hosts:

ansible all — list-hosts

Now we can check the connectivity using ping command;

ansible all -m ping

Now, we have to dynamically load the variable file named same as OS_name which could be RedHat or Ubuntu and just by using the variable names we can Configure our target node

To check the variable name, we can take a help of setup module as;

ansible all -m setup

If I will run this it will list the complete details of both the IP

To check the detail of RedHat, we can use [redhat] group ip and for Ubuntu the [ubuntu] group respectively;

ansible redhat -m setup

also for Ubuntu

ansible ubuntu -m setup

after running this here we can see the OS name is stored in a variable ansible_distribution which is a sub part of variable ansible_facts

which can be written as ansible_facts[‘distribution’]

So, now to perform this task we are going to configure apache web server on both the OS so, lets create 2 variables file name as RedHat.yml and Ubuntu.yml (Make sure to use the same name as it is case sensitive)

vim RedHat.yml

As, we know in Redhat for Apache Web server the software name is httpd

vim Ubuntu.yml

And, in Ubuntu the software name is apache2

Now, the index.html file:

vim index.html

Now, let’s write the main playbook i’m giving a name as rhel-ubuntu.yml

vim rhel-ubuntu.yml

Now, let’s run the playbook

ansible-playbook rhel-ubuntu.yml

Done! Now if we will check the webserver is configured or not!!

https://ip:80

That’s all

Code Link: GitHub

Thank you!

--

--