patternbashansibleModerate
Ansible inventory: static files, dynamic inventory scripts, and grouping strategies
Viewed 0 times
amazon.aws collection >= 5.0 for modern aws_ec2 plugin
inventorydynamic inventoryaws_ec2 pluginhost groupsgroup_varskeyed_groupsinventory plugin
aws
Error Messages
Problem
Managing server inventory as a static flat file does not scale when hosts are ephemeral (cloud instances that come and go). Teams end up with stale inventory files that reference non-existent hosts and miss new ones.
Solution
Use dynamic inventory plugins for cloud environments. For AWS, use the
Static inventory (
Dynamic inventory (
Run with dynamic inventory:
aws_ec2 plugin which queries the EC2 API for instances matching filters and groups them by tags, region, and instance type.Static inventory (
inventory/hosts.ini):[webservers]
web1.example.com ansible_user=ubuntu
web2.example.com ansible_user=ubuntu
[dbservers]
db1.example.com ansible_user=ubuntu
[production:children]
webservers
dbserversDynamic inventory (
inventory/aws_ec2.yml):plugin: amazon.aws.aws_ec2
regions:
- us-east-1
filters:
instance-state-name: running
tag:Environment: prod
keyed_groups:
- key: tags.Role
prefix: role
- key: placement.region
prefix: region
hostname_source: ip-addressRun with dynamic inventory:
ansible-inventory -i inventory/aws_ec2.yml --list
ansible-playbook -i inventory/aws_ec2.yml site.ymlWhy
Dynamic inventory sources reflect the real state of your cloud environment. Tag-based grouping (e.g.,
role_webserver, role_database) allows playbooks to target the correct instances without manual inventory maintenance.Gotchas
- Dynamic inventory requires the cloud provider collection to be installed (
ansible-galaxy collection install amazon.aws) - SSH connectivity must be available from the Ansible controller to all target hosts — use a bastion host or VPN for private subnets
- Group variables (
group_vars/webservers.yml) apply to hosts in that group from both static and dynamic inventory - Cache dynamic inventory with
cache: truein the plugin config to avoid API rate limits during large runs
Context
Managing Ansible inventory for cloud environments with ephemeral instances
Revisions (0)
No revisions yet.