Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Write a playbook that behaves differently on Ubuntu and RHEL hosts.

IntermediateHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: all
  become: true
  tasks:
    - name: Load OS-specific vars
      ansible.builtin.include_vars: "{{ ansible_facts['os_family'] }}.yml"
      # Debian.yml: pkg_name: apache2   RedHat.yml: pkg_name: httpd

    - name: Install web server
      ansible.builtin.package:
        name: "{{ pkg_name }}"
        state: present

    - name: Open firewall on RHEL
      ansible.posix.firewalld:
        service: http
        permanent: true
        immediate: true
        state: enabled
      when: ansible_facts['os_family'] == "RedHat"

Key trick → The generic package module plus per-OS var files avoids an apt task and a yum task for every package. os_family groups distros (Debian covers Ubuntu, RedHat covers Rocky and Alma).

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks