Created 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.
I could have easily solved this used case by using when keyword but to understand ,How more We can easily trick things in playbook and to solve any used cases is always a good thing .
Here I took help of ansible facts and a little manipulation in the playbook
What We want :-
My used case was to build a dynamic playbook which would automatically fetch the OS name and its Version and would work as the name of variable Yaml file .Here I only created a Yaml file of name RedHat and Ubuntu and version of OS 8 and 20 respectively because for demonstration to this practical am using RHEL-8 and Ubuntu-20, In both the file I created multiple variables for package ,Document root path and name of the service of that specific OS supports .Later it would fetch all the details from that specific OS Yaml file to my main playbook .In my playbook ,I instructed to install and start the service of Apache web server .
Which all OS I used for this practical .
I used RHEL 8 (192.168.43.76) , Ubuntu (192.168.43.158).
Here is my Inventory file
The following steps to be done ..
STEP 1
I created two Variable_seprated Yaml file with Name and Version of two of the OS I used
Redhat-8.yml
In Redhat-8.yml file ,I defined three variable
package_name: httpd
document_root: /var/www/html/index.html
service_name: httpd
Ubuntu-20.yml
In Ubuntu-20.yml file ,I defined three variable
package_name: apache2
document_root: /var/www/html/index.html
service_name: apache2
STEP 2
I created a Playbook named package.yml .In that playbook I used vars_files module .
Instead of giving any file name hardcoded ,here I used ansible_facts and fetch the OS name and Version ,Normally after the output comes out .It would automatically find the variable according to which OS facts belong and configure as we created the variable file.
Here I used vars function as I want that my playbook would dynamically find out which OS it is and in that OS what webpage I want to deploy.
STEP 3
I used package module and in name attribute I used package_name variable which I defined in all of my variable_file .To fetch package_name value I used jinja .
STEP 4
I used template module and in dest attribute I used document_root variable which I defined in all variable_file .To fetch document_root value I used jinja .
In Webpage folder , I created name of Web page same as OS name .They would belong.
STEP 5
I used service module and in name attribute I used service_name variable which I defined in all variable_file .To fetch service_name value I used jinja .
STEP 6
Here I used debug module to show the variable value to get a better understanding .