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.
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:
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”.
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:
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):