Servers are autoscaled in AWS and IPs change daily. How do you keep the inventory accurate?
IntermediateScenarioInventory and Targeting
Answer
Situation read → A static file will always be stale; the source of truth is the cloud API.
What I'd do →
- Use the
amazon.aws.aws_ec2inventory plugin. - Group by tags with
keyed_groups, and use private IPs as the connection address. - Enable caching so repeated runs are quick.
# inventories/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [ap-south-1]
filters:
tag:Env: prod
instance-state-name: running
keyed_groups:
- key: tags.Role
prefix: role
compose:
ansible_host: private_ip_address
cache: true
cache_timeout: 300
Why → Instances join groups automatically through tags, so new nodes get configured without editing any file.
Interview tip → The file name must end in aws_ec2.yml or aws_ec2.yaml for the plugin to accept it.
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?BeginnerA 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.IntermediateYou want to run a task on every host in the `db` group and also on localhost in the same playbook.Beginner