Stage 4 · Provision
Dynamic Inventory & Scale
Constructed & Composite Inventory
keyed_groups, compose, and merging multiple sources.
Constructed Inventory Plugin
The constructed inventory plugin transforms existing inventory data. It creates groups from host attributes, computes variables, and restructures inventory without querying external sources.
---
plugin: ansible.builtin.constructed
strict: yes
groups:
# Group by OS family
debian: ansible_os_family == "Debian"
redhat: ansible_os_family == "RedHat"
# Group by environment tag
production: environment == "production"
staging: environment == "staging"
# Group by role
web: role == "webserver"
db: role == "database"
compose:
# Compute custom variables
ansible_port: 22
ssh_key: "'~/.ssh/ansible_key'"
# Format hostnames
short_name: inventory_hostname.split('.')[0]The constructed plugin evaluates expressions against existing host variables and creates new groups and variables dynamically.
keyed_groups
keyed_groups:
# Group by a variable value
- key: ansible_distribution
prefix: distro
separator: "_"
# Group by a tag
- key: tags.Environment
prefix: env
separator: "_"
# Group by availability zone
- key: placement.availability_zone
prefix: az
separator: "_"
# Group by instance type with transform
- key: instance_type | regex_replace('t3\.', 't3-')
prefix: type
separator: "_"keyed_groups create dynamic groups by extracting values from host attributes. The prefix and separator control group naming.
compose Expressions
compose:
# Conditional variable
ansible_user: "'admin' if ansible_os_family == 'Debian' else 'ec2-user'"
# Computed value
memory_gb: ansible_memtotal_mb | int / 1024
# List from fact
installed_services: ansible_facts.services.keys() | list
# Boolean flag
is_container: ansible_virtualization_type == "docker"compose expressions use Jinja2 syntax to compute new variables from existing facts. These variables are available in playbooks.
composite Variables
composite:
# Build a host metadata dictionary
host_metadata:
hostname: inventory_hostname
ip: ansible_default_ipv4.address | default(ansible_host)
os: ansible_distribution ~ " " ~ ansible_distribution_version
role: tags.Role | default("unknown")
env: tags.Environment | default("unknown")
# Build a list of all hosts in the same group
peer_hosts: groups['webservers'] | map('extract', hostvars, 'ansible_host') | listcomposite variables let you build complex data structures from multiple sources. They are useful for templates and reporting.
Merging Multiple Sources
[defaults]
inventory = ./static.yml, ./dynamic.ymlAnsible merges multiple inventory sources. Static and dynamic inventories are combined, with later sources overriding earlier ones.
Constructed inventory lets you restructure any inventory source. Use it to create logical groups from cloud tags, compute variables from facts, or merge multiple sources into a unified view.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.