Interview Prep/Ansible/Inventory and Targeting

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 →

  1. Use the amazon.aws.aws_ec2 inventory plugin.
  2. Group by tags with keyed_groups, and use private IPs as the connection address.
  3. 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.

All Ansible questions Roadmap: Ansible

More on Inventory and Targeting