Dynamically changing variables based on OS distro in Ansible Playbook

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>
<title>Another simple example</title>
@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;
<h1>Hello there!</h1>

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

- hosts: webservers
- pkg_names:
- "{{ansible_os_family | lower }}.yaml"
- name: Load var file depending on the os family
include_vars: "{{ lookup('first_found', pkg_names) }}"
- name: "Install the {{pkg_name}} package"
name: "{{pkg_name}}"
state: present
- name: copy the webserver files from localhost to the servers
src: ./pages/index.html
dest: /var/www/html/
- restart httpd
- name: "start the {{pkg_name}} service"
name: "{{pkg_name}}"
state: started
- name: restart httpd
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. 😃



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store