Interview Prep/Ansible/Inventory and Targeting

A playbook must target different hosts depending on a variable passed at the command line.

IntermediateScenarioInventory and Targeting
Answer

Situation read → The target is a parameter, for example a CI job input.

What I'd do → Template hosts: from an extra var, with a safe default.

- hosts: "{{ target | default('none') }}"
  gather_facts: false
  tasks:
    - ansible.builtin.ping:
ansible-playbook deploy.yml -e target=web:\&mumbai

Why → Extra vars are available when the play's hosts are resolved; defaulting to none means a forgotten variable does nothing instead of hitting all.

Interview tip → Contrast with --limit, which narrows rather than defines.

All Ansible questions Roadmap: Ansible

More on Inventory and Targeting