What is dynamic inventory?
Dynamic inventory builds the host list by querying a cloud API. When instances are created, terminated, or get new IPs, Ansible sees the current set automatically.
| Static inventory | Dynamic inventory |
|---|---|
Hand-edited inventory.ini | Queried from AWS |
| Breaks when IPs change | Tracks autoscaling |
| Fine for tiny labs | Production cloud fleets |
Ansible → AWS API → Fetch EC2 → Build inventory
Install dependencies (control node)
sudo apt update
sudo apt install -y python3-pip awscli
pip3 install boto3 botocore
ansible-galaxy collection install amazon.aws
ansible-galaxy collection list | grep amazon.awsAWS credentials
Create an IAM user (lab: AmazonEC2ReadOnlyAccess is enough for inventory). Generate access keys, then:
aws configure
aws sts get-caller-identityInventory plugin file
# aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions:
- ap-southeast-1
filters:
instance-state-name: running
hostnames:
- public-ip-address
- private-ip-address
compose:
ansible_host: public_ip_addressansible-inventory -i aws_ec2.yml --graph
ansible-inventory -i aws_ec2.yml --list
ansible all -i aws_ec2.yml -m pingGroup by tags
Tag instances, for example Environment=production.
plugin: amazon.aws.aws_ec2
regions:
- ap-southeast-1
keyed_groups:
- key: tags.Environment
prefix: env
filters:
instance-state-name: runningansible -i aws_ec2.yml env_production -m ping
ansible-playbook -i aws_ec2.yml playbooks/nginx.yml --limit env_productionFilter examples
filters:
instance-state-name: running
tag:Role: webUse with a playbook
ansible-playbook -i aws_ec2.yml playbooks/nginx.ymlMini project
- Tag two EC2 hosts (
Environment=dev/production) - Build
aws_ec2.ymlwithkeyed_groups - Ping only
env_production - Run a playbook limited to that group
Interview: dynamic inventory queries the cloud so Ansible always targets current instances — critical for autoscaling and ephemeral IPs.