Ansible playbook and different os variable files

Ansible playbook provides the RAL(Resource Abstraction Layer) as its main feature so that one don’t need to worry about the respective os commands. For example to install the apache server on the ubuntu the command is

apt-get install apache2

and to install the apache server on the redhat8 the command is

yum install httpd

But in ansible one package module do everything.

# for redhat
- hosts: ip or host group
tasks:
- package:
name: "httpd"
state: present
# for ubuntu
- hosts: ip or host group
tasks:
- package:
name: "apache2"
state: present

Now here are following challenges in the code:

  • For the same task writing the different plays for the different os increases the length of the code.
  • Remembering the different package names while writing the playbook is difficult. (I am talking about a big code or a big playbook not just about my demo code)

We can use the when keyword to avoid from writing the another play:

- hosts: host group
tasks:
- package:
name: "httpd"
state: present
when: ansible_facts['distribution']=="RedHat"
- service:
name: "httpd"
state: started
when: ansible_facts['distribution']=="RedHat"
- package:
name: "apache2"
state: present
when: ansible_facts['distribution']=="Ubuntu"
- service:
name: "httpd"
state: started
when: ansible_facts['distribution']=="Ubuntu"

Above way is not efficient as we are repeating ourselves in the code and putting away from the main agenda.

Implementing the following objective will help us to solve the challenges in the code.

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.

RedHat-8.yml for Redhat :

package: httpd

Ubuntu-18.yml for Ubuntu:

package: apache2

The playbook: main.yml

The inventory: hosts.txt

Running playbook

Outputs:

Conclusion: vars files in ansible are of great use for the dynamic environment.

Learning Practicing Exploring