Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 29 ยท Getting Started

Inventory: Hosts and Groups

Learn Ansible inventory files in INI and YAML: groups, children, ranges, host patterns, ansible-inventory, group_vars and host_vars, and dynamic inventory.

Before Ansible can configure anything, it needs to know which machines exist and how to reach them. That list is the inventory. At its simplest, an inventory is a text file with host names. In real projects it also groups hosts ("web servers", "database servers", "production"), and attaches variables to hosts and groups, such as the SSH user or the port an application listens on.

A good inventory is the foundation of everything that follows: playbooks say "run this on the web group" and the inventory decides which machines that means. This lesson covers the two file formats, groups and children, ranges, the pattern language you use to pick hosts, the group_vars and host_vars folders, and the idea behind dynamic inventories.

An INI inventory

The classic format is INI. Host names go on lines, and [name] starts a group:

INI
# inventory/hosts.ini
bastion.example.com

[web]
web1.example.com
web2.example.com

[db]
db1.example.com ansible_port=2222
db2.example.com
  • bastion.example.com appears before any group, so it belongs only to the built-in group ungrouped.
  • web1 and web2 are members of web; db1 and db2 are members of db.
  • ansible_port=2222 is a host variable set inline on one line. Other special connection variables are ansible_host (the real address if the name is just a label), ansible_user and ansible_ssh_private_key_file.

Two groups always exist without being written: all (every host) and ungrouped (hosts in no other group).

A YAML inventory

The same inventory in YAML is more verbose but handles nested data better:

YAML
# inventory/hosts.yml
all:
  hosts:
    bastion.example.com:
  children:
    web:
      hosts:
        web1.example.com:
        web2.example.com:
    db:
      hosts:
        db1.example.com:
          ansible_port: 2222
        db2.example.com:

Each host is a key. A host with no variables ends in a colon and nothing else. Use whichever format your team prefers; INI is shorter for small cases, YAML is easier to generate and to extend with structured variables. You can even keep several files in one directory and pass the directory to -i.

Groups of groups

A group can contain other groups with the :children suffix in INI, or children: in YAML. This lets you organize hosts along more than one axis, such as role and environment:

INI
[web]
web1.example.com
web2.example.com

[db]
db1.example.com

[staging]
web2.example.com

[prod:children]
web
db

Here prod contains every host of web and db. A host can belong to many groups at once: web2 is in web, in staging and (through web) in prod. Targeting prod reaches web1, web2 and db1.

flowchart TD
    prod --> web
    prod --> db
    web --> w1["web1"]
    web --> w2["web2"]
    db --> d1["db1"]
    staging --> w2

A host such as web2 can sit in several groups: web (and so prod) and staging.

Ranges

Numbered or lettered hosts need not be typed one by one. Square brackets define a range:

INI
[web]
web[01:03].example.com      # web01, web02, web03 (leading zero kept)

[cache]
cache-[a:c].example.com     # cache-a, cache-b, cache-c

Ranges work in INI and in YAML host keys.

Host patterns: choosing hosts

Wherever Ansible asks "which hosts?" (the first word of an ad-hoc command, the hosts: line of a play, the --limit option) you give a pattern:

Pattern Meaning
all or * Every host
web Hosts in the web group
web1.example.com One host
web:db Union: web or db
web:&prod Intersection: in web and in prod
prod:!staging Exclusion: in prod but not in staging
*.example.com Wildcard on names
web[0], web[0:1] By position inside the group (counting from 0, slices include the end)
~web\d+ A regular expression, starting with ~

You can combine them: prod:&web:!web2.example.com. In a shell, quote patterns that contain ! or &, for example 'web:!staging', because the shell treats those characters specially.

Ask Ansible what a pattern matches before you run anything risky:

Terminal
ansible 'prod:!staging' -i inventory/hosts.ini --list-hosts
TEXT
  hosts (2):
    web1.example.com
    db1.example.com

Looking at the whole inventory

ansible-inventory prints what Ansible understood, after parsing, merging and applying variables:

Terminal
ansible-inventory -i inventory/hosts.ini --graph
TEXT
@all:
  |--@db:
  |  |--db1.example.com
  |  |--db2.example.com
  |--@ungrouped:
  |  |--bastion.example.com
  |--@web:
  |  |--web1.example.com
  |  |--web2.example.com

The groups appear in alphabetical order, whatever order you wrote them in.

Use --list for a full JSON dump (hosts, groups and variables), --host web1.example.com for the variables of one host, and -y to print YAML instead of JSON. When something behaves strangely, this is the first place to check, and it works the same for every kind of inventory, including dynamic ones.

group_vars and host_vars

Putting many variables inside the inventory file gets messy. Ansible lets you place them in files named after the group or host, in folders next to the inventory (or next to the playbook):

TEXT
project/
  inventory/
    hosts.ini
    group_vars/
      all.yml            # applies to every host
      web.yml            # applies to the web group
      prod.yml
    host_vars/
      db1.example.com.yml   # applies to one host only
YAML
# inventory/group_vars/web.yml
http_port: 8080
app_user: deploy
YAML
# inventory/host_vars/web1.example.com.yml
http_port: 9090

The more specific place wins: a host variable overrides a group variable, and a child group overrides its parent. So web1 listens on 9090 while web2 uses 8080. The complete precedence order has many more levels; it is explained in Variables, Facts and Precedence.

Keep one inventory per environment (inventories/dev, inventories/prod), each with its own group_vars. You then switch environments by changing a single -i option. The multi-tier project builds exactly this layout.

Dynamic inventory

Servers in the cloud appear and disappear, so a static file goes stale. A dynamic inventory asks an outside source (a cloud API, a CMDB, a virtualization platform) for the current hosts each time you run. In current Ansible this is done with inventory plugins: you write a small configuration file naming the plugin, and Ansible builds the groups for you from tags or labels. From the playbook's point of view nothing changes: it still targets groups like web. Performance, Dynamic Inventory and AWX shows how this looks in practice.

A stand-in: parse an INI inventory and expand patterns

The program below is a small, simplified version of what Ansible does: it reads INI text, expands ranges, resolves :children groups, and evaluates patterns with :, :& and :!. Real Ansible supports far more (regexes, positions, many edge cases); the point is to see the logic.

JS Parsing an INI inventory and resolving patterns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the range web[01:03] produced three hosts with the leading zero kept, that prod has no hosts of its own and yet includes both web and db through :children, and that staging is just another group that cuts across the others.

A stand-in: which value wins?

Variables set at several levels need a rule. This second stand-in applies the simplest part of it: all, then the parent group, then the child group, then the host. Later layers override earlier ones. (Real Ansible has more layers; they come in the variables lesson.)

JS Host variables override group variables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

web1 ends with port 9090 because the host layer comes last, web2 gets 8080 from web, and db1 keeps 8000 from prod. With your inventory in place, you can start running real commands in Ad-Hoc Commands.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A host is written before any [group] header in an INI inventory. Which group is it in?

    Hosts outside every named group belong to the built-in group ungrouped. Every host is also a member of all.
  2. 2. What does the pattern prod:!staging select?

    The colon separates terms, and !group removes that group's hosts from the result built so far.
  3. 3. How do you make a group prod contain the groups web and db in an INI inventory?

    The :children suffix means the lines below are group names, not hosts. :vars would define variables instead.
  4. 4. web1 sets http_port in host_vars and its group web sets a different http_port in group_vars. Which value does web1 use?

    Host variables override group variables. Ansible prefers the more specific definition.
  5. 5. Which command shows the groups of an inventory as a tree?

    ansible-inventory --graph prints the group tree, --list prints JSON with variables, and --host shows the variables of one host.

Summary

  • The inventory lists hosts and groups; INI is compact, YAML handles structure better.
  • all and ungrouped always exist; :children builds groups of groups; ranges like web[01:03] generate host names.
  • Host patterns combine groups with : (union), :& (intersection) and :! (exclusion); check them with --list-hosts.
  • ansible-inventory --graph, --list and --host show what Ansible really sees.
  • group_vars/ and host_vars/ folders keep variables out of the inventory file, and the more specific level wins.
  • Dynamic inventory plugins build the host list from external sources such as cloud APIs.

Next: Ad-Hoc Commands