Run Ansible Tasks Based on OS Distribution
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
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:
greys@maverick:~/proj/ansible $ ansible stream -m setup| grep 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”.
Example of using ansible_distribution
- name: Register RHEL 8 against Tech Stack shell: "subscription-manager register --activationkey=rhel8 --org=100XXXXX --force" tags: - rhel when: 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):
greys@maverick:~/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] PLAY RECAP * stream : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0