Making use of Ansible Facts and Variables to configure httpd webserver without using when keyword in the Ansible playbook
Task Description 📄
🔰 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.( Note: No need to use when keyword here. )
Solution Steps:-
Step 1:- First I run below command ,for proper connectivity and retrieve ansible_facts of Redhat system.
ansible <host-ip> -m setup | less
Setup module help us to find out OS specific version and it’s names .
Run above command and Just put your OS specific variable file name as ansible_distribution_name and ansible_distribution_version name.
- We know that ansible treat every words as a case sensitive so we can’t give variable file name randomly. Because according to ansible “redhat” and “Redhat” both are different words.
- Now rename your file and put name as ansible_distribution and version. For example……..RedHat-8.0.yml .
Redhat-8.0 variable file
software_name: httpd
service_name: httpd
doc_root: /var/www/html
Step 2:- Create the following playbook for setting up apache web server using ansible facts and variables.
- hosts: redhat
vars_files:
- "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_version'] }}.yml"
tasks:
- name: Installing software
package:
name: "{{ software_name }}"
state: present
- name: Copy index.html file
template:
dest: "{{doc_root}}/index.html"
src: /root/ws2/index.html
- name: Stating service
service:
name: "{{service_name}}"
state: started
In first line, Ansible decides that which file need to include according to it’s distribution name and version.
- hosts: redhat
vars_files:
- "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_version'] }}.yml"
This step setup the web server on top of Redhat depending on their variable file name and version.
tasks:
- name: Installing software
package:
name: "{{ software_name }}"
state: present
- name: Copy index.html file
template:
dest: "{{doc_root}}/index.html"
src: /root/ws2/index.html
- name: Stating service
service:
name: "{{service_name}}"
state: started
Here is my index.html file which I’m copying with the help of template module.
This is {{ ansible_facts['distribution'] }}.{{ ansible_facts['distribution_major_version']}} operating system
Step 3:- Running the Ansible-Playbook
Output of code
Hence, the web page is successfully deployed, just by the use of ansible facts and variables.