Sometimes you might want to execute a certain Ansible Playbook only on servers with a specific OS. Since Ansible collects the OS in the
gathering facts stage, you can easily do this in a
Read Information from Gathering Facts
gathering facts collects a lot of information about the target-host. You can display them like this.
ansible -m setup <servername>
These information are stored in variables and can be used like every other variable in your Ansible-Code.
Example: Package Update
A prime example of OS specific tasks is to update packages. In this Example we want to update Dabian via
apt and CentOS and RedHat via
The Playbook for this could look like this.
host: localhost gather_facts: true tasks: - name: run apt ansible.builtin.apt: name: '*' state: latest when: ansible_distribution == "Debian" - name: run yum ansible.builtin.yum: name: '*' state: latest when: ansible_distribution == "CentOS" or ansible_distribution == "RedHat"