Load variable files in ansible dynamically according to the OS name to configure the target node without using when keyword

Deepanshu Yadav
2 min readApr 10, 2021

🎇Above is the ansible playbook. Here if you see in the vars_files, i haven’t written directly the file name i want to include, in fact, gave a variable and hence we took advantage of ansible_facts and this variable would retrieve os name, and we have written the packages, etc in a file with giving the same name as os name in the same folder. As shown below, we have 2 files RedHat.yml and Ubuntu.yml and these are also the os name. See below👇

🔰Now, right now i am in the redhat os and if i run this file in localhost, RedHat.yml file would be included. Let’s run and see🔰

✨See, ansible has determined that this is redhat os and hence used the RedHat.yml file and finally httpd web server is configured in this os and you can see it.✨

🍤Now lets take an ubuntu os and run the same playbook there. I am just changing the ip in playbook and you will see that this time Ubuntu.yml file would be included and apache2 will be installed.🍤

so, that’s what we wanted🔥

Thanks for your time.😊

code for reference👇

- hosts: 13.233.183.41:qvars_files:
- "{{ ansible_facts['distribution'] }}.yml"
tasks:
- debug:
var: "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_version'] }}"
- debug:
msg: this is {{ ansible_facts['distribution'] }} OS
- package:
name: "{{ package }}"
state: present
- service:
name: "{{ package }}"
state: started

--

--