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.
More on Inventory and Targeting
You are handed a fresh Ansible project and 10 servers. How do you make sure Ansible can reach all of them before writing any playbook?BeginnerYour team keeps prod and staging hosts in one inventory file and someone ran a playbook on prod by mistake. How do you prevent it?IntermediateYou need to run a playbook on only the web servers in Mumbai that are not in the canary group. How?BeginnerServers are autoscaled in AWS and IPs change daily. How do you keep the inventory accurate?IntermediateA host is reachable by SSH on port 2222 with a different user from all others. How do you model that?BeginnerYou must configure servers in a private subnet that is only reachable through a bastion.Intermediate