A teammate asks for a group that contains all hosts that have more than 16 GB RAM.
AdvancedScenarioInventory and Targeting
Answer
Situation read → Group membership depends on facts, which exist only at run time.
What I'd do → Use group_by after fact gathering.
- hosts: all
tasks:
- ansible.builtin.group_by:
key: "bigmem_{{ ansible_memtotal_mb > 16384 }}"
- hosts: bigmem_True
tasks:
- ansible.builtin.debug: { msg: "large host" }
Why → group_by builds groups in memory for the rest of the run; inventory files cannot know facts in advance.
Interview tip → Alternatively use the constructed inventory plugin with cached facts for a persistent version.
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