Split up Ansible playbook using Ansible facts

I wanted to run some actions against Centos and some against debian machines.

---
  
- hosts: all
  tasks:

  - name: "Group the servers by operating system and version."
    group_by:
      key: os_{{ ansible_distribution }}

- hosts: os_CentOS
  tasks:

  - name: "Install packages on CentOS"
    yum:
      name: "{{ item.name }}"
      state: "{{ item.state }}"
    with_items:
      - { name: epel-release, state: present }
      - { name: net-tools, state: present }
      - { name: finger, state: present }
      - { name: htop, state: present }
      - { name: sudo, state: present }
      - { name: chrony, state: absent }

- hosts: os_Debian
  tasks:

  - name: "Install packages on Debian"
    apt:
      name: "{{ item.name }}"
      state: "{{ item.state }}"
    with_items:
      - { name: net-tools, state: present }
      - { name: finger, state: present }
      - { name: htop, state: present }
      - { name: sudo, state: present }

Offcourse there are many ways to do it. you could also use

---

- hosts: all
  tasks:
  - name: Install on specific os
    include: '{{ item }}'
    with_first_found:
      - files:
        - 'install_packages_{{ ansible_pkg_mgr }}.yml'

and then you will also need offcourse:

  • install_packages_yum.yml
  • install_packages_apt.yml