Dynamically changing variables based on OS distro in Ansible Playbook

Meherchaitanya
3 min readMar 28, 2021

--

When it comes to some applications like webserver application from apache which has package name as httpd in RedHat based distros and apache2 in Debian based distros. Ansible cannot be intelligent in this case. but with the help of variables and facts, we can make ansible change the names depending on the distro or os_family of the managed nodes.

So, now most of the distros come into the family of RedHat or Debian. So I have created two files to store variables for redhat and debian based distros named as redhat.yaml and debian.yaml

And I have an index.html file in the pages directory which is in the same directory as the main.yaml file. Below is my sample html code.

<!DOCTYPE html>
<html>
<head>
<title>Another simple example</title>
</head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Raleway:wght@800&display=swap');
body {
display: flex;
margin: 0;
justify-content: center;
align-items: center;
}
h1 {
text-align: center;
font-size: 32px;
font-family: "Raleway", sans-serif;
}
</style>
<body>
<h1>Hello there!</h1>
</body>
</html>

Now we can get into the main.yaml file. we need to

- hosts: webservers
vars:
- pkg_names:
files:
- "{{ansible_os_family | lower }}.yaml"
tasks:
- name: Load var file depending on the os family
include_vars: "{{ lookup('first_found', pkg_names) }}"
- name: "Install the {{pkg_name}} package"
package:
name: "{{pkg_name}}"
state: present
- name: copy the webserver files from localhost to the servers
copy:
src: ./pages/index.html
dest: /var/www/html/
notify:
- restart httpd
- name: "start the {{pkg_name}} service"
service:
name: "{{pkg_name}}"
state: started
handlers:
- name: restart httpd
service:
name: "{{pkg_name}}"
state: restarted
  • Here in the above code, first i created a variables of the file names depending on the distros being used.
  • Then I created a task to include the variable depending up on the os distro
  • Now the installation and setup is same as the normal setup of httpd in the RedHat that I did in the previous blogs.
  • I also added a handler that restarts the apache webserver when the files inside the server have changed

As you can see, the same configuration is done to both of the instances even though the names of the packages are different.

Hope you liked this article and found it useful. 😃

--

--

Meherchaitanya
Meherchaitanya

Written by Meherchaitanya

Love DevOps and Web Development

No responses yet