Q: You manage 500+ AWS EC2 instances across multiple environments. How do you implement Ansible AWS dynamic inventories with keyed groups and tag filtering for zero maintenance?
Replace static hosts files with the official amazon.aws.aws_ec2 YAML inventory plugin. Query live AWS APIs to discover instances dynamically, filter by running states, and organize hosts using keyed_groups based on AWS tags.
Want to master this scenario in a live sandbox? KodeKloud's CKA & CKAD Hands-On Certification Track covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Create Declarative aws_ec2.yml Config
Configure the official AWS collection inventory plugin file (must end with aws_ec2.yml or aws_ec2.yaml):
- Specify plugin:
plugin: amazon.aws.aws_ec2 - Define target regions:
regions: [us-east-1, eu-west-1] - Filter out terminated or stopping instances:
filters: { instance-state-name: running } - Resolve hostnames via private IP:
hostnames: [private-ip-address]
Construct Dynamic Groups Using AWS Tags
Automatically classify instances into Ansible host groups based on their AWS resource tags:
keyed_groups:-
- key: tags.Environmentprefix: env→ createsenv_production,env_staging -
- key: tags.Roleprefix: role→ createsrole_webserver,role_api
Verify and Target Dynamic Fleets
Audit the discovered infrastructure tree before executing configuration updates:
- Verify inventory tree:
ansible-inventory -i aws_ec2.yml --graph - Inspect metadata in JSON:
ansible-inventory -i aws_ec2.yml --list - Execute playbook against dynamic group:
ansible-playbook -i aws_ec2.yml deploy.yml --limit 'role_webserver:&env_production'
- Static inventory files fail in autoscaling architectures where instance IDs and IP addresses change constantly.
- Deploy the 'amazon.aws.aws_ec2' inventory plugin configured in 'aws_ec2.yml' with live AWS API queries.
- Filter instances to only running states: 'filters: instance-state-name: running'.
- Generate dynamic host groups using 'keyed_groups' mapped to AWS tags (Environment, Role, Service).
- Set 'hostnames: private-ip-address' for secure private VPC communication via bastion/VPN.
- Validate discovered infrastructure with 'ansible-inventory -i aws_ec2.yml --graph' before launching playbooks.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Naming the inventory file without the required aws_ec2.yml suffix Ansible's auto plugin detection ignores files that do not match the *aws_ec2.yml naming pattern.
- Defaulting to public IP hostnames for instances in private subnets Private EC2 instances lack public IPs; playbooks fail with connection timeouts unless private-ip-address is declared.
- Failing to filter instance-state-name: running Ansible attempts to connect over SSH to stopped and terminating instances, causing timeouts and failed plays.