Managing Environments with vars_files in Ansible

Managing Environments with vars_files in Ansible

Hi there! Today we are going to see some more cool concepts in ansible. So let's get right into it.

Problem Statement

Sometimes we have some use cases where we have to configure an application say web server on multiple hosts and we can do that easily with ansible if they are all same host using the same version of the application but the problem arises when we have to configure webserver on completely different distributions (Debian and Redhat) or same distribution but having different versions (Centos 7 and Centos 8).

So we might face an issue like in the above example in Debian systems apache package name for webserver is apache2 but in Redhat based systems the same package is called httpd and also env variables and stuff might differ too.

So how to solve this problem efficiently?

Solution

To solve this kind of use case we can use the concept of vars_files along with jinja templating in ansible to include the os specific files at the run time of playbook.

It will be like this when ansible is configuring Redhat then the RedHat variable file will be included and when Ubuntu is being configured then Ubuntu specific variables will be included dynamically at the run-time.

So let's see how it is done. I have created a playbook which looks like this.

Screenshot (1029).png

You can see it here

Also in version_files folder, I have created two separate files each for one OS which container OS-specific variables and stuff. Here's how they look like.

VirtualBox_Ansible Controller Redhat_28_12_2020_17_38_22.png

VirtualBox_Ansible Controller Redhat_28_12_2020_17_40_02.png

VirtualBox_Ansible Controller Redhat_28_12_2020_17_39_43.png

So now let's run the playbook and see what we get.

VirtualBox_Ansible Controller Redhat_28_12_2020_17_13_13.png

As you can see the respective packages have been configured on each OS and now let's check how they are running.

VirtualBox_Ansible Controller Redhat_28_12_2020_17_13_51.png

VirtualBox_ubuntu_28_12_2020_17_14_14.png

Services are running fine. Now let's see the webpages

Screenshot (1027).png

Screenshot (1028).png

All things are configured successfully and are up and running. So this way we can configure and manage multi-environment setups using ansible.

That's it for this one.See you next time..!!!

Did you find this article valuable?

Support Written Wisdom by becoming a sponsor. Any amount is appreciated!