Run Ansible Tasks Based on OS Distribution

Ansible playbook with Red Hat tag Skipping Tasks based on OS-specific Ansible Conditionals

I’m actively refreshing my Ansible setup for both servers and desktops, running mostly Red Hat Enterprise Linux and CentOS Linux. Today’s quick tip is about the functionality that Ansible has for precise control of configuration management in such closely related distros.

How To Run Ansible Task In Specific OS Distribution

Ansible has quite a few facts it collects about each managed system, they are usually established (collected) at the very start of running any playbook (unless you decide to skip gathering facts).

A whole group of Ansible facts talks about OS distribution. Here they are as confirmed form the freshly deployed CentOS 8 Stream VM:

One of these facts is ansible_distribution:

[email protected]:~/proj/ansible $ ansible stream -m setup| grep distribution
"ansible_distribution": "CentOS",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/redhat-release",
"ansible_distribution_file_variety": "RedHat",
"ansible_distribution_major_version": "8",
"ansible_distribution_release": "Core",
"ansible_distribution_version": "8.0",

We can use the very first one, called ansible_distribution. For CentOS, it says “CentOS”, but for Red Hat Enterprise Linux, it will be “RedHat”.

Example of using ansible_distribution

I have the following task below. It’s activating RHEL 8 subscription using my account, but obviously should only be doing this for Red Hat systems. For CentOS, I simply want to skip this task.

That’s why I’m checking for ansible_distribution, and as per below – the code will only run if and when the distribution is speficially RedHat, and not CentOS as my “stream” VM:

- name: Register RHEL 8 against Tech Stack
  shell: "subscription-manager register --activationkey=rhel8 --org=100XXXXX --force"
  tags: - rhel
  ansible_distribution == "RedHat"

That’s it! Even if I specify the tags=rhel filter, ansible-playbook will skip this task based on the collected facts (stream is the VM hostname):

[email protected]:~/proj/ansible $ ansible-playbook --tags=rhel vm.yaml
PLAY [Tech Stack baseline] _\*\*
TASK [Gathering Facts] _
ok: [stream]
TASK [techstack : Register RHEL 8 against Tech Stack]
skipping: [stream]
stream : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

See Also

Keep Learning

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative I'm also a fan of SetApp for macOS: SetApp for macOS
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
31 Jan 2023

Homelab: MacBook Pro M2

17 Nov 2022

Video: awk delimiters

25 Oct 2022

macOS Ventura 13.0

Recent Tweets