TExcelTAD
Home › Configuration Management: Ansible › Dynamic Inventories: Scripts & Plugins

Dynamic Inventories: Scripts & Plugins

In the cloud, servers come and go: an auto-scaling group adds three instances at 9:00 and removes them at 18:00. A hand-written host list is out of date within the hour. A dynamic inventory asks the source of truth (the cloud API, Terraform state, a CMDB, NetBox) at the start of every run.

Ansible has two mechanisms:

Inventory script Inventory plugin
what it is any executable that prints JSON a Python plugin, configured with a small YAML file
examples your own script, older ec2.py amazon.aws.aws_ec2, azure.azcollection.azure_rm, google.cloud.gcp_compute, community.general.proxmox, netbox.netbox.nb_inventory, constructed
caching, filters, grouping write it yourself built in
recommended for small, special sources yes, for anything a plugin exists for

Writing an inventory script

The contract is small. Called with --list, the script prints every group with its hosts and variables, plus a _meta.hostvars map (so Ansible doesn't call it again once per host with --host <name>). The script must be executable.

This one pretends to ask a CMDB; in real life the dictionary would come from an HTTP API:

bash · try it yourself
cat > cmdb.py <<'PY'
#!/usr/bin/env python3
"""Inventory script: prints the CMDB as Ansible inventory JSON."""
import json
import sys

SERVERS = [  # in real life: requests.get(CMDB_URL).json()
    {"name": "web-a", "ip": "10.0.1.10", "role": "web", "env": "prod"},
    {"name": "web-b", "ip": "10.0.1.11", "role": "web", "env": "prod"},
    {"name": "db-a", "ip": "10.0.2.10", "role": "db", "env": "prod"},
    {"name": "web-s", "ip": "10.1.1.10", "role": "web", "env": "staging"},
]

def inventory():
    inv = {"_meta": {"hostvars": {}}}
    for s in SERVERS:
        for group in (s["role"], s["env"]):
            inv.setdefault(group, {"hosts": []})["hosts"].append(s["name"])
        inv["_meta"]["hostvars"][s["name"]] = {"ansible_host": s["ip"], "env": s["env"]}
    return inv

if len(sys.argv) == 2 and sys.argv[1] == "--list":
    print(json.dumps(inventory(), indent=2))
elif len(sys.argv) == 3 and sys.argv[1] == "--host":
    print(json.dumps({}))  # everything is already in _meta
else:
    sys.exit("usage: cmdb.py --list | --host NAME")
PY
chmod +x cmdb.py
./cmdb.py --list | jq -c '.web, ._meta.hostvars["db-a"]'
echo "=== as Ansible sees it"
ansible-inventory -i cmdb.py --graph
ansible -i cmdb.py 'web:&staging' --list-hosts
{"hosts":["web-a","web-b","web-s"]}
{"ansible_host":"10.0.2.10","env":"prod"}
=== as Ansible sees it
@all:
  |--@ungrouped:
  |--@web:
  |  |--web-a
  |  |--web-b
  |  |--web-s
  |--@prod:
  |  |--web-a
  |  |--web-b
  |  |--db-a
  |--@db:
  |  |--db-a
  |--@staging:
  |  |--web-s
  hosts (1):
    web-s

Ansible recognised cmdb.py as a script because it is executable. A script can be in a folder with static files too; -i inventory/ merges them all.

Inventory plugins

A plugin is configured by a YAML file whose name must end in the suffix the plugin expects, and whose plugin: key names it. For AWS:

yaml
# inventory/aws_ec2.yml  (the file name must end in aws_ec2.yml or aws_ec2.yaml)
plugin: amazon.aws.aws_ec2
regions: [eu-west-1]
filters:
  instance-state-name: running
  tag:Project: linkly
keyed_groups:
  - key: tags.Role            # an instance tagged Role=web joins group role_web
    prefix: role
  - key: placement.availability_zone
    prefix: az
hostnames:
  - tag:Name
  - private-ip-address
compose:
  ansible_host: private_ip_address
cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: ~/.cache/ansible-inventory
cache_timeout: 300

With credentials in the environment (an instance profile, AWS_PROFILE, or OIDC in CI), the output looks like this. It is a sample session, because the sandbox has no AWS account:

bash
$ ansible-inventory -i inventory/aws_ec2.yml --graph
@all:
  |--@ungrouped:
  |--@aws_ec2:
  |  |--web-1
  |  |--web-2
  |  |--db-1
  |--@role_web:
  |  |--web-1
  |  |--web-2
  |--@role_db:
  |  |--db-1
  |--@az_eu_west_1a:
  |  |--web-1
  |  |--db-1
  |--@az_eu_west_1b:
  |  |--web-2

Tag your instances in Terraform (tags = { Role = "web", Project = "linkly" }) and the groups appear by themselves. The Terraform lesson builds on this.

The constructed plugin: groups from variables

ansible.builtin.constructed adds groups and variables to hosts that other inventory sources already provided. It is the offline twin of keyed_groups above, so you can try it here. Inventory sources in a folder are read in alphabetical order, which is why the files are numbered:

bash · try it yourself
mkdir inventory
cat > inventory/01-hosts.yml <<'YML'
all:
  hosts:
    web-a: {os_version: "24.04", env: prod, cpu: 2}
    web-b: {os_version: "22.04", env: prod, cpu: 8}
    db-a:  {os_version: "24.04", env: staging, cpu: 16}
  vars:
    ansible_connection: local
YML
cat > inventory/02-constructed.yml <<'YML'
plugin: ansible.builtin.constructed
strict: true
keyed_groups:
  - key: env
    prefix: env
  - key: os_version
    prefix: ubuntu
groups:
  big: cpu >= 8
compose:
  workers: cpu * 2
YML
ansible-inventory -i inventory --graph
ansible-inventory -i inventory --host web-b | jq -c '{env, workers}'
@all:
  |--@ungrouped:
  |--@env_prod:
  |  |--web-a
  |  |--web-b
  |--@ubuntu_24_04:
  |  |--web-a
  |  |--db-a
  |--@big:
  |  |--web-b
  |  |--db-a
  |--@ubuntu_22_04:
  |  |--web-b
  |--@env_staging:
  |  |--db-a
{"env":"prod","workers":16}

keyed_groups turns a variable's value into a group name (24.04 became ubuntu_24_04: invalid characters are replaced with _), groups adds hosts to a group when a Jinja2 condition is true, and compose creates new variables. strict: true turns errors in those expressions into failures instead of silently skipping the host.

Test yourself

What must an inventory script print when called with --list?

  1. One hostname per line
  2. JSON with groups and hosts, ideally with _meta.hostvars
  3. An INI file
  4. YAML with plugin:

In an aws_ec2 plugin file, what does keyed_groups: [{key: tags.Role, prefix: role}] do?

  1. Filters out instances without a Role tag
  2. Puts each instance in a group named after its Role tag, e.g. role_web
  3. Sets ansible_host
  4. Caches the inventory

Why prefer an inventory plugin over a custom script for AWS?

  1. Scripts are not supported any more
  2. The plugin has filters, grouping, hostnames and caching built in and is maintained with the collection
  3. Plugins don't need credentials
  4. Plugins are faster to write