Interview Prep/Ansible/Inventory and Targeting

You want a group of hosts derived from a variable, like every host with `env: prod` in its host_vars.

AdvancedScenarioInventory and Targeting
Answer

Situation read → Persistent grouping derived from variables, not facts.

What I'd do → Use the constructed inventory plugin alongside the static inventory.

# inventories/constructed.yml
plugin: ansible.builtin.constructed
strict: false
keyed_groups:
  - key: env
    prefix: env
groups:
  prod_web: env == 'prod' and 'web' in group_names

Why → The plugin builds groups from hostvars at parse time, so every command sees the same groups.

Interview tip → Put it in the inventory directory; it is loaded after the other sources.

All Ansible questions Roadmap: Ansible

More on Inventory and Targeting