When running an Ansible playbook (or roles) it becomes a little bit irksome to have to create new playbooks just because a device may have a different operating system. Thankfully the awesome people behind Ansible have a solution for this.
A Little Background…
I have my inventory set in a file called “inventory” in the same location I am calling Ansible from. This inventory file contains a few different devices running different operating systems.
The Ansible command:
ansible -i inventory all -m setup -a "filter=ansible_distibution"
returns information from the devices around the operating system family (ansible_distribution) and the Python interpreter (discovered_interprerter_python) on the device.
For more detail try:
ansible -i inventory all -m setup -a "filter=ansible_distibution*"
This will return the same information as the first command but will also return:
ansible_distribution_file_variety
ansible_distribution_major_version
ansible_distribution_release
So for my Pi this came back as:
ansible_distribution: Debian ansible_distribution_file_variety: Debian ansible_distribution_major_version: 10 ansible_distribution_release: buster
Where as a device running Ubuntu (19.10) came back as:
ansible_distribution: Ubuntu ansible_distribution_file_variety: Debian ansible_distribution_major_version: 19 ansible_distribution_release: eoan
Before writing a playbook to use this information I would recommend using the commands a few times on various systems to see if what comes back is what you expected.
Putting It Into Action
For this example I’m going to use an inventory containing three devices. A CentOS device, an Ubuntu device and a Debian device. I want to place a directory on each device but that directory is unique to the operating system (OS), i.e. I want to place a directory called test_centos only on the CentOS machine.

The line:
when: ansible_facts['distribution']=="DISTRIBUTION_NAME"
tells Ansible only to use that play of the playbook if the distribution matches. This means that each of the 3 plays in this playbook will make 1 change and skip 2, i.e. the CentOS folder will be created on the CentOS device and skipped on the Ubuntu and Debian devices. Then then Ubuntu folder will be created on the Ubuntu device but skipped on the CentOS and Debian devices.
The playbook (“ansible_when_example.yml“) for this blog post is available via my GitHub repository: https://github.com/geektechdude/AWS_Ansible_Playbooks
You must be logged in to post a comment.