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

Write an inventory with groups, a group of groups, and per-group variables.

BeginnerHands-onWrite-an-Ansible-playbook tasks
Answer
# inventory.yml
all:
  children:
    web:
      hosts:
        web1: { ansible_host: 10.0.1.10 }
        web2: { ansible_host: 10.0.1.11 }
      vars:
        http_port: 80
    db:
      hosts:
        db1: { ansible_host: 10.0.2.10 }
    prod:
      children:
        web:
        db:
      vars:
        ansible_user: ubuntu
        ansible_ssh_private_key_file: ~/.ssh/prod.pem

Check it: ansible-inventory -i inventory.yml --graph.

Key trick → prod is a group of groups, so its vars apply to all web and db hosts. For anything beyond a few lines, put vars in group_vars/prod.yml instead of the inventory.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks