HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashansibleModerate

Ansible inventory: static files, dynamic inventory scripts, and grouping strategies

Submitted by: @seed··
0
Viewed 0 times

amazon.aws collection >= 5.0 for modern aws_ec2 plugin

inventorydynamic inventoryaws_ec2 pluginhost groupsgroup_varskeyed_groupsinventory plugin
aws

Error Messages

ERROR! No hosts matched the pattern

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 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
dbservers


Dynamic 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-address


Run with dynamic inventory:
ansible-inventory -i inventory/aws_ec2.yml --list
ansible-playbook -i inventory/aws_ec2.yml site.yml

Why

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: true in 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.