Skip to content

Ansible: Dynamic inventory from AWS

Simple case

# cat inventory/aws_ec2.yml

plugin: amazon.aws.aws_ec2

regions:
  - eu-central-1

filters:
  "instance-state-name": "running"

keyed_groups:
  - key: ec2_tags.Environment
    prefix: ""
    separator: ""
    default_key: Environment
    default_value: untagged

hostnames:
  - tag:Name

compose:
  ansible_host: instance_id
  ansible_user: "'admin'"
  ansible_connection: "'ssh'"
  ansible_ssh_common_args: >-
    -o ProxyCommand='sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"'
  Name: ec2_tags.Name | default('unnamed', true)
  aws_environment: ec2_tags.Environment | default('untagged', true)
  internal_lan_ip: private_ip_address

strict: false

Checking inventory:

ansible-inventory -i inventory/aws_ec2.yml --graph

Troubleshooting

Groups by tags do not created in inventory

Normal output:

# ansible-inventory -i inventory/aws_ec2.yml --graph
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--domain-wg
  |  |--domain-dev
  |  |--domain-runners
  |  |--domain-prod
  |--@infra:
  |  |--domain-wg
  |  |--domain-runners
  |--@dev:
  |  |--domain-dev
  |--@prod:
  |  |--domain-prod

Invalid output:

# ansible-inventory -i inventory/aws_ec2.yml --graph
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--domain-wg
  |  |--domain-dev
  |  |--domain-runners
  |  |--domain-prod
The root cause: old aws ansible collection version

Solution: install aws collection >= 11.4

# cat requirements.yml
---
collections:
  - name: amazon.aws
    version: "11.4.0"

# Execute as the user account under which Ansible runs
ansible-galaxy collection install -r requirements.yml --force

# ansible-galaxy collection list amazon.aws

# /home/ghr/.ansible/collections/ansible_collections
Collection Version
---------- -------
amazon.aws 11.4.0