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:
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:
I learn with Educative:
I'm also a fan of 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!