Include Tasks depending on the OS

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 when condition.

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.

Check for specific Distribution

name: Check for specific Distribution
when: ansible_distribution == "Debian" or ansible_distribution == "Ubuntu"

Check for Major Version

name: Check for Major Version
when: anible_distribution_major_version == 12

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 yum. The Playbook for this could look like this.

host: localhost
gather_facts: true
    - name: run apt
        name: '*'
        state: latest
      when: ansible_distribution == "Debian"
    - name: run yum
        name: '*'
        state: latest
      when: ansible_distribution == "CentOS" or ansible_distribution == "RedHat"
profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.