You inherited a 400-line INI inventory with repeated variables. How do you clean it up without breaking anything?
IntermediateScenarioInventory and Targeting
Answer
Situation read → Refactor with a safety net: the effective variables per host must not change.
What I'd do →
- Snapshot:
ansible-inventory -i old --list > before.json. - Move shared variables into
group_vars/and per-host ones intohost_vars/. - Snapshot again and diff.
ansible-inventory -i inventory --list > after.json
diff <(jq -S . before.json) <(jq -S . after.json)
Why → ansible-inventory --list shows merged hostvars, so an empty diff proves the refactor is behaviour-neutral.
Interview tip → Use --graph --vars for a quick human-readable view of the group tree.
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