Skip to main content

Infrastructure as code · Advanced · 22 min

Find your EC2 servers automatically with an Ansible dynamic inventory

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0 · amazon.aws 12.1.0 · boto3 1.44.12 · AWS CLI 2.42.4

You will replace a hand-kept host list with the amazon.aws EC2 inventory plugin, so Ansible finds running instances by tag, groups them by role and environment, connects on their private addresses and caches the answer, using an IAM policy that only allows the reads it needs.

On this page

A static inventory is a promise that someone will update a file every time a server is launched, replaced or retired. On AWS that promise breaks quickly. An Auto Scaling group swaps an instance overnight, a colleague launches a second web server from the console, and the next playbook run either misses the new machine or times out on one that no longer exists.

The amazon.aws collection ships an inventory plugin, aws_ec2, that asks EC2 for the list each time Ansible runs. You describe which instances you want and how to group them, and the plugin builds the inventory from the tags already on your instances. Nothing to keep in sync by hand.

In this tutorial you will:

  • launch four small, tagged instances to practise on
  • write an aws_ec2 inventory file that only picks up running instances from this project
  • turn the Role and Env tags into Ansible groups, name hosts from their Name tag and connect on private addresses
  • run a play against role_web:&env_production
  • cache the listing so repeated runs do not query AWS every time
  • write an IAM policy that lets Ansible read the inventory and do nothing else

Nothing here logs in to the instances: every play uses gather_facts: false and the debug module, which runs on your control machine. The instances still cost money while they exist, so the last step terminates them.

Step 1 · Install Ansible, the AWS collection and the AWS CLI

Install pipx, then ansible-core 2.22.0 in its own environment. The inventory plugin talks to AWS through boto3, and it must be installed in Ansible's Python, not the system one, so add it with pipx inject:

Bash
sudo apt update
sudo apt install -y pipx curl unzip ca-certificates openssh-client
pipx install ansible-core==2.22.0
pipx inject ansible-core boto3==1.44.12 botocore==1.44.12
export PATH="$HOME/.local/bin:$PATH"

Add the PATH line to ~/.bashrc (or run pipx ensurepath and open a new terminal) so the commands are found next time. Now install the collection that holds the plugin, pinned so your results match this page:

Bash
ansible-galaxy collection install amazon.aws==12.1.0

Then the AWS CLI, which you use to launch and tag the practice instances. uname -m prints x86_64 or aarch64, which matches the names of Amazon's installer files:

Bash
cd "$(mktemp -d)"
AWS_CLI_VERSION=2.42.4
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
cd ~

If the AWS CLI is already installed, the installer says so; run sudo ./aws/install --update instead. None of these tools get updates from apt. Upgrade later with pipx upgrade ansible-core, pipx inject ansible-core --force boto3 botocore, ansible-galaxy collection install --upgrade amazon.aws, and the AWS CLI installer with a newer version number. The collection and the AWS libraries add up to a large download, so on a metered or prepaid connection do this step once on a good link.

Check it worked

Bash
ansible-inventory --version | head -n 1
ansible-galaxy collection list amazon.aws
pipx runpip ansible-core show boto3 | head -n 2
aws --version

You see ansible-inventory [core 2.22.0], a line amazon.aws 12.1.0 under your collections path, Name: boto3 with Version: 1.44.12, and aws --version starting with aws-cli/2.42.4.

Step 2 · Launch four tagged instances to find

The plugin works from tags, so the instances need consistent ones. These four use the scheme you will group by: Role says what the server does, Env which environment it belongs to, Name what to call it, and Project marks everything this tutorial creates so you can find and delete it later.

Point the AWS CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder). Then check which account you are in:

Bash
aws sts get-caller-identity

The output shows the account ID and the user or role you are signed in as. Make sure it is the sandbox account before you launch anything.

Make the project folder and a small demo.env file that remembers the Region and the image to launch, so later commands and new terminals can read them back. The image is the current Ubuntu 26.04 AMI, looked up from the public parameter Canonical maintains in each Region:

Bash
mkdir -p ~/ec2-inventory-demo
cd ~/ec2-inventory-demo
export AWS_REGION=eu-west-2
Bash
AMI_ID=$(aws ssm get-parameter \
  --name /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id \
  --query Parameter.Value --output text)
Bash
cat > demo.env <<EOF
export AWS_REGION=${AWS_REGION}
export AMI_ID=${AMI_ID}
EOF
cat demo.env

The examples use eu-west-2 (London). Any Region works if you use the same one everywhere, including the inventory file in the next step. If you work from Africa and your account has Cape Town (af-south-1) turned on, it is closer; it is an opt-in Region, so an administrator has to enable it first.

Now launch the instances. Each is a t3.micro in the default VPC, with no key pair, because nothing in this tutorial logs in:

Bash
for spec in web-1:web:production web-2:web:production db-1:db:production web-stg-1:web:staging; do
  IFS=: read -r NAME ROLE ENV <<< "$spec"
  aws ec2 run-instances --image-id "$AMI_ID" --instance-type t3.micro --count 1 \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}},{Key=Role,Value=${ROLE}},{Key=Env,Value=${ENV}},{Key=Project,Value=ec2-inventory-demo}]" \
    --query 'Instances[0].InstanceId' --output text
done
aws ec2 wait instance-running --filters Name=tag:Project,Values=ec2-inventory-demo

The loop prints four instance IDs, and the wait returns once all of them are running.

Check it worked

Bash
aws ec2 describe-instances \
  --filters Name=tag:Project,Values=ec2-inventory-demo \
  --query 'Reservations[].Instances[].[Tags[?Key==`Name`]|[0].Value, State.Name, PrivateIpAddress]' \
  --output table

A table lists web-1, web-2, db-1 and web-stg-1, each running with a private address from your default VPC (something like 172.31.x.x).

Step 3 · Write the inventory file and filter by tag and state

A hand-kept inventory for these servers would look like this, with every address typed in and every change made by hand:

YAML
all:
  children:
    web:
      hosts:
        web-1: { ansible_host: 172.31.10.21 }
        web-2: { ansible_host: 172.31.10.22 }

The dynamic version names a plugin instead of hosts. The file name must end in aws_ec2.yml (or .yaml), or Ansible will not hand it to the plugin:

Bash
cd ~/ec2-inventory-demo
mkdir -p inventory
cat > inventory/demo.aws_ec2.yml <<'YAML'
plugin: amazon.aws.aws_ec2
regions:
  - eu-west-2
filters:
  tag:Project: ec2-inventory-demo
  instance-state-name: running
hostnames:
  - tag:Name
  - instance-id
use_deprecated_tags: false
YAML

What each part does:

  • regions lists where to look. Leave it out and the plugin asks for every Region the account can use, which is slower and needs one more permission.
  • filters uses the same filter names as aws ec2 describe-instances --filters. All entries must match. If you do not filter on instance-state-name, the plugin includes stopped instances by default, and Ansible then tries to reach machines that are switched off.
  • hostnames is a preference list. Each host is named after its Name tag; one without a Name tag falls back to its instance ID instead of being dropped.
  • use_deprecated_tags: false stops the plugin adding an old tags variable alongside ec2_tags, and the warning that comes with it.

Check it worked

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

The tree shows @all, an @aws_ec2 group the plugin always creates, and web-1, web-2, db-1 and web-stg-1 under it.

Now stop the staging server, as if it were switched off for the night, and ask again:

Bash
. ./demo.env
STG_ID=$(aws ec2 describe-instances \
  --filters Name=tag:Name,Values=web-stg-1 Name=tag:Project,Values=ec2-inventory-demo \
  --query 'Reservations[0].Instances[0].InstanceId' --output text)
aws ec2 stop-instances --instance-ids "$STG_ID"
aws ec2 wait instance-stopped --instance-ids "$STG_ID"
ansible-inventory -i inventory/demo.aws_ec2.yml --graph

web-stg-1 has gone from the tree; the other three remain. Nobody edited a file.

Step 4 · Turn tags into groups and connect on private addresses

One flat aws_ec2 group is not much use. keyed_groups makes a group for each value of a variable, and compose sets connection variables from the instance data. Replace the inventory file with this version:

Bash
cat > inventory/demo.aws_ec2.yml <<'YAML'
plugin: amazon.aws.aws_ec2
regions:
  - eu-west-2
filters:
  tag:Project: ec2-inventory-demo
  instance-state-name: running
hostnames:
  - tag:Name
  - instance-id
use_deprecated_tags: false

keyed_groups:
  - key: ec2_tags.Role
    prefix: role
  - key: ec2_tags.Env
    prefix: env

compose:
  ansible_host: private_ip_address
YAML

ec2_tags is a dictionary of each instance's tags, so ec2_tags.Role is web or db, and with the prefix the groups become role_web and role_db. The same goes for env_production. An instance with no Role tag is left out of the role groups rather than causing an error, because strict is false by default. Turn on strict: true once every instance is tagged, so a typo in the file fails loudly instead of quietly producing an empty group.

compose sets ansible_host to the private address. The inventory name stays web-1, which is what you see in output and use in --limit, while SSH goes to the address. Private addresses are right when your control machine is inside the VPC, on a VPN into it, or in CI running in the same network. If you connect from outside, use public_dns_name instead, and make sure your security groups allow it.

Check it worked

Bash
ansible-inventory -i inventory/demo.aws_ec2.yml --graph
ansible-inventory -i inventory/demo.aws_ec2.yml --host web-1

The tree now has @env_production, @role_db and @role_web groups, with web-1 and web-2 under @role_web and db-1 under @role_db. The --host output is a long JSON object of everything EC2 knows about web-1; near the top, ansible_host holds the same private address the table in step 2 showed for it, and ec2_tags lists its four tags.

Step 5 · Run a play against the groups the tags made

Playbooks use these groups like any others. A pattern such as role_web:&env_production means "in role_web and also in env_production", so a staging web server tagged the same way can never be caught by a production run.

Bash
cat > report.yml <<'YAML'
- name: List the production web servers
  hosts: role_web:&env_production
  gather_facts: false
  tasks:
    - name: Show where Ansible would connect
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} -> {{ ansible_host }} ({{ ec2_tags.Env }}, {{ instance_type }})"
YAML
ansible-playbook -i inventory/demo.aws_ec2.yml report.yml

Every value in the message comes from EC2, not from a file you wrote: instance_type and the addresses are host variables the plugin sets, and ec2_tags holds the tags. Use them in when: conditions and templates in the same way.

To reach the servers for real, each instance needs a key pair or another way in (EC2 Instance Connect, or SSM Session Manager with its own connection plugin), and a security group that admits your control machine. Then the usual first check is a ping:

Bash
ansible -i inventory/demo.aws_ec2.yml 'role_web:&env_production' -m ansible.builtin.ping -u ubuntu

Check it worked

The play prints two msg lines, one for web-1 and one for web-2, each with an address, production and t3.micro. The recap at the end lists exactly those two hosts. db-1 and the stopped staging server do not appear.

Step 6 · Cache the listing between runs

Each Ansible command makes the plugin call EC2 again. With a few Regions and many instances that adds seconds to every run, and on a slow or metered link the calls add up. Inventory caching saves the instance listing to disk and reuses it until it expires. Add the cache settings to the end of the inventory file:

Bash
cat >> inventory/demo.aws_ec2.yml <<'YAML'

cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: ~/.cache/ec2-inventory-demo
cache_timeout: 300
YAML
ansible-inventory -i inventory/demo.aws_ec2.yml --graph > /dev/null
ls ~/.cache/ec2-inventory-demo

ls shows one file, whose name starts with ansible_inventory_ and ends with a short key derived from the inventory file path. For 300 seconds after it was written, Ansible reads the listing from that file instead of asking EC2. The plugin still makes one small call per Region to look up Availability Zone IDs, so it needs working credentials even when the cache is fresh.

The cost of a cache is staleness. Launch a fifth server and look at the inventory:

Bash
aws ec2 run-instances --image-id "$AMI_ID" --instance-type t3.micro --count 1 \
  --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=web-3},{Key=Role,Value=web},{Key=Env,Value=production},{Key=Project,Value=ec2-inventory-demo}]" \
  --query 'Instances[0].InstanceId' --output text
aws ec2 wait instance-running --filters Name=tag:Name,Values=web-3
ansible-inventory -i inventory/demo.aws_ec2.yml --graph

web-3 is running, but the tree does not show it: Ansible answered from the cache. Tell it to throw the cache away and ask EC2 again:

Bash
ansible-inventory -i inventory/demo.aws_ec2.yml --graph --flush-cache

ansible-playbook takes the same --flush-cache flag. Pick a timeout that fits how often your fleet changes: a few minutes for an Auto Scaling group, longer for a handful of long-lived servers. Run with --flush-cache straight after you launch or replace instances.

Check it worked

The first --graph after the launch lists three hosts and no web-3. The run with --flush-cache lists web-3 under @role_web next to web-1 and web-2.

Step 7 · Give Ansible only the permissions the inventory needs

Whatever credentials run Ansible, a CI role or the instance profile of a control server, should be able to list instances and nothing more. For the file you wrote, the plugin makes two kinds of call: ec2:DescribeInstances for the listing and ec2:DescribeAvailabilityZones for the zone IDs it adds to each host. It needs ec2:DescribeRegions only if you leave regions empty. Other permissions are needed only when you turn on the matching options: ssm:GetInventory for use_ssm_inventory, and Route 53 list permissions for route53_enabled.

Write the policy:

Bash
cat > ansible-inventory-policy.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadEc2Inventory",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances",
        "ec2:DescribeAvailabilityZones"
      ],
      "Resource": "*"
    }
  ]
}
JSON

"Resource": "*" looks broad, but EC2 Describe actions cannot be limited to particular instances; AWS only accepts * for them. The policy is still narrow because every action in it is a read. It cannot start, stop or change anything.

Create it in IAM and keep its ARN for the clean-up:

Bash
aws iam create-policy --policy-name ansible-ec2-inventory-read \
  --policy-document file://ansible-inventory-policy.json \
  --query Policy.Arn --output text > policy-arn.txt
cat policy-arn.txt

Attach it to the role your control machine or CI job uses, for example with aws iam attach-role-policy --role-name <your-ansible-role> --policy-arn "$(cat policy-arn.txt)" (replace the placeholder). The playbooks themselves log in over SSH, so they need no AWS permissions at all unless a task calls AWS modules.

Check it worked

Bash
aws iam get-policy-version --policy-arn "$(cat policy-arn.txt)" --version-id v1 \
  --query 'PolicyVersion.Document.Statement[0].Action'

The output lists exactly ec2:DescribeInstances and ec2:DescribeAvailabilityZones. Once the policy is attached, run ansible-inventory --graph --flush-cache with that role's credentials: the same tree appears, and an attempt such as aws ec2 stop-instances with those credentials fails with UnauthorizedOperation.

Step 8 · Terminate the instances and remove the policy

Terminating deletes instances and their root volumes permanently. First list what the Project tag matches, and check that every ID belongs to this tutorial:

Bash
cd ~/ec2-inventory-demo
. ./demo.env
aws ec2 describe-instances \
  --filters Name=tag:Project,Values=ec2-inventory-demo Name=instance-state-name,Values=pending,running,stopping,stopped \
  --query 'Reservations[].Instances[].InstanceId' --output text | tr '\t' '\n' > instance-ids.txt
cat instance-ids.txt

You see five IDs, including the stopped staging server. Then terminate them and wait until they are gone:

Bash
xargs aws ec2 terminate-instances --output text --query 'TerminatingInstances[].InstanceId' --instance-ids < instance-ids.txt
xargs aws ec2 wait instance-terminated --instance-ids < instance-ids.txt

If you attached the policy to a role, detach it first with aws iam detach-role-policy, then delete it. Finally remove the project folder and the cache, which deletes only what this tutorial created:

Bash
aws iam delete-policy --policy-arn "$(cat policy-arn.txt)"
cd ~
rm -rf ~/ec2-inventory-demo ~/.cache/ec2-inventory-demo

Keep Ansible and the collection if you will use them again. Otherwise run pipx uninstall ansible-core, and remove the collection with rm -rf ~/.ansible/collections/ansible_collections/amazon if nothing else on this machine uses it.

Check it worked

Bash
aws ec2 describe-instances \
  --filters Name=tag:Project,Values=ec2-inventory-demo Name=instance-state-name,Values=pending,running,stopping,stopped \
  --query 'length(Reservations[].Instances[])'
test ! -e ~/ec2-inventory-demo && echo "demo folder removed"

The count is 0 and the last line prints demo folder removed. Terminated instances stay visible in the EC2 console for about an hour with the state terminated; they no longer bill.

Next steps

  • Keep variables for these generated groups in group_vars/role_web/ and group_vars/env_production/ next to the inventory file: /tutorials/organise-ansible-variables-with-group-vars-and-host-vars.
  • Launch and log in to an instance by hand, to see the key pair and security group pieces this tutorial skipped: /tutorials/launch-an-ec2-instance-and-connect.
  • Point a full playbook at the role_web group once you can reach the servers: /tutorials/configure-a-server-with-an-ansible-playbook.
  • Split that playbook into roles that each group applies: /tutorials/organise-ansible-work-into-roles.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.