From charlesreid1

It is useful to group machines by distribution, and it is possible to define these groups without explicitly doing so in the inventory file.

The following example playbook uses a group_by keyword and sets the group by key to the operating system distribution.

 - name: talk to all hosts just so we can learn about them
   hosts: all
   tasks:
     - name: Classify hosts depending on their OS distribution
       group_by:
         key: os_{{ ansible_facts['distribution'] }}

 # now just on the CentOS hosts...

 - hosts: os_CentOS
   gather_facts: False
   tasks:
     - # tasks that only happen on CentOS go here

Now you can define tasks that are specific to an operating system, by limiting the hosts attribute of the task.

Further, you can also apply grup-specific settinggs for different operating systems:

---
# file: group_vars/all
asdf: 10

---
# file: group_vars/os_CentOS
asdf: 42

If variables are the only thing you need, you can define the variables in the files as above, and then just define the variables file name based on the OS distribution:

- hosts: all
  tasks:
    - name: Set OS distribution dependant variables
      include_vars: "os_{{ ansible_facts['distribution'] }}.yml"
    - debug:
        var: asdf

(Note that this first defines the include file containing variables, then runs a simple debug task that prints the value of the variable asdf.)

Flags