How do `keyed_groups`, `hostnames` and `compose` shape an `aws_ec2` inventory?

AdvancedConceptInventory
Answer
  • keyed_groups builds groups from instance attributes, for example one group per tag value.
  • hostnames chooses the inventory name, tried in order (tag:Name, private-ip-address, dns-name).
  • compose creates host variables from Jinja2 expressions over the instance data.
plugin: amazon.aws.aws_ec2
regions: [ap-south-1]
keyed_groups:
  - key: tags.Role
    prefix: role         # group role_web, role_db
  - key: placement.availability_zone
    prefix: az
hostnames:
  - tag:Name
  - private-ip-address
compose:
  ansible_host: private_ip_address
  env: tags.Env | default('unknown')

Now hosts: role_web:&az_ap_south_1a works without anyone maintaining a list.

All Ansible questions Roadmap: Ansible

More on Inventory