Ansible Dynamically Loads Operating System Specific Variable File

Muhammad Tabish Khanday
3 min readJul 19, 2021

In this blog, I will demonstrate how I created an Ansible Playbook which will dynamically load the variable file named the same as the Operating System of the managed node, and just by using the variable names we can Configure our managed nodes.

Ansible Directory Structure.

Below is my directory structure for my ansible workspace:

Ansible configuration file:

$ vim ansible.cfg

For this demo, I used the AWS cloud to launch 3 managed Nodes with 3 different Operating Systems wiz:

  1. Redhat Linux 8
  2. Ubuntu 20.04
  3. Amazon Linux 2

Ansible Inventory file:

$ vim inventory

Let’s check the Ansible facts on each managed node:

$ ansible -m setup amazon2 | grep distribution

$ ansible -m setup ubuntu| grep distribution

$ ansible -m setup redhat| grep distribution

The next step is to create variable files with names the same as the distribution for the variables that we will use in our playbook.

$ vim vars/Redhat.yml

$ vim vars/Ubuntu.yml

$ vim vars/Amazon.yml

The last step is to create a playbook and run the playbook. In the playbook, we can use vars_file keyword and ansible facts to import OS-specific files.

$ vim setup.yml

$ ansible-playbook setup.yml

Let’s check the webpage on the browser.

Voilà, we have successfully created a playbook that dynamically loads the variable file named the same as the Operating System of the managed node, and just by using the variable names, we can Configure our managed nodes.

GitHub: https://github.com/mtabishk/ansible-playbooks/tree/main/load_os_specific_files

That’s all for this article, Hope You learned Something from here.

Thanks, everyone for reading. I’ll be back with some new articles very soon, thanks!

Muhammad Tabish Khanday

LinkedIn: https://www.linkedin.com/in/mtabishk/

--

--