Lesson 2 of 13 · 22m
Inventories: Groups, Variables, and Dynamic Sources
Static and dynamic inventories, group_vars/host_vars layering, and the limit patterns that turn all-of-prod into one canary.
Every catastrophic Ansible run I've been called into started in the inventory, not the playbook. "Why did postgres restart on the app server?" — because app03 was also listed under [dbservers], and a play targeting dbservers does what it says. The inventory is the schema of your fleet; the playbook is just a query that trusts it.
The static file, done honestly
# inventories/production/hosts.ini
[webservers]
web[01:04].prod.acme.corp
[dbservers]
db01.prod.acme.corp primary=true
db02.prod.acme.corp
[prod:children]
webservers
dbserversweb[01:04] expands to four hosts — the range syntax keeps a 40-node group one line long. [prod:children] makes prod a group-of-groups, so hosts: prod hits both tiers and group_vars/prod.yml applies to both. The primary=true on db01 is an inline host variable — acceptable for a boolean flag, a smell the moment it's longer than a word.
Two things the file format hides. A host can live in unlimited groups; membership is union, never exclusive — that's the app03 failure mode, and Ansible won't warn you because overlapping groups are a feature. And duplicate definitions silently merge: if web01 appears under [webservers] twice with different inline vars, both apply.
Patterns are a query language
ansible-playbook site.yml -l 'webservers:&prod' # intersection: webservers AND prod
ansible-playbook site.yml -l 'webservers:!web02*' # exclusion: all web nodes except web02*
ansible-playbook site.yml -l 'webservers[0]' # first host — the poor man's canary
ansible-playbook site.yml -l 'webservers[:2]' # first two — a batch: or , unions, & intersects, ! excludes, [n] slices. This is how "canary to one node, then roll" works without editing a single file. Quote the pattern — ! and & are shell metacharacters.
group_vars and host_vars: the layering that actually resolves
inventories/production/
group_vars/
all.yml # NTP servers, sysctl baseline — every host
webservers.yml # nginx worker count, TLS paths
dbservers.yml # shared_buffers, wal_level
host_vars/
db01.prod.acme.corp.yml # maintenance_window: tuesdayResolution order: group_vars/all < the host's groups (deeper/more specific group wins) < host_vars. "Configured on db01 but not db02" is almost always a host_vars/ file someone left behind. ansible-inventory --host db01.prod.acme.corp prints the resolved variable set — the single most underused debugging command in the tool — and ansible-inventory --graph draws the tree when the nesting gets clever.
Dynamic inventory: when the file rots in a week
The moment autoscaling or a CMDB exists, a checked-in list is a lie with a timestamp. Inventory plugins query the source of truth at runtime:
# inventories/production/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [us-east-1]
keyed_groups:
- key: tags.Environment
prefix: env # produces groups like env_prod
- key: tags.Role
prefix: role # produces role_web, role_db
filters:
instance-state-name: runningSame mechanism exists for GCP (gcp_compute), Azure (azure_rm), VMware (vmware_vm_inventory), and NetBox — the file is YAML, the truth is the API. Two production details that bite: keyed groups normalize tag values (a tag of web-prod becomes group role_web_prod), and the constructed plugin composes new groups and variables from other inventories' results — "every host whose facts say Debian AND whose tag says prod" without tagging discipline from anyone.
Every run re-queries the API unless you turn on the plugin's cache: cache: true with cache_plugin: jsonfile and a cache_timeout in the same YAML keeps a 600-host inventory from costing you a paginated API call per host per run.
localhost, the escape hatch
localhost with ansible_connection: local runs on the control node — the standard pattern for "provision the thing, then configure the thing" (create the EC2 instance locally, add it with add_host, configure it in the next play). It works because local short-circuits the whole SSH story from the first lesson.
Field notes
- Secrets in inventory vars go through vault or a vaulted
vault.yml— plaintextgroup_vars/all.ymlis exactly how DB passwords end up in git history. ansible-inventory --listdumps the full resolved inventory as JSON; pipe tojqbefore you accuse the pattern of being wrong.- A dynamic inventory and a static file can coexist in one
-idirectory — transition state during a CMDB migration is a supported shape, not a hack.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.