Aurora Store's inventory is already well organized in inventory/hosts.yml, but it still mixes two different things: which machines exist (hosts and groups) and what data each one has (variables). While there are only two connection variables it doesn't get in the way, but soon you will need the store's domain, the nginx port, the PostgreSQL version, different settings for each server… Putting all of that in hosts.yml would turn it into a huge, unreadable file. In this lesson you will learn to split variables out into the group_vars/ and host_vars/ directories, define Aurora's first configuration variables, understand which value wins when a variable is defined in several places and, at last, solve the mystery left open in lesson 1.5: why the inventory's ansible_user was winning over the -u option.

Contents

  1. Why move variables out of the inventory file
  2. The group_vars/ and host_vars/ directories
  3. Standalone files or subdirectories
  4. Aurora Store's variables
  5. Checking variables: ansible-inventory and the debug module
  6. Basic precedence: all, group and host
  7. Ties between groups: depth, alphabetical order and ansible_group_priority
  8. The open case: ansible_user versus -u
  9. Saving your work in git

  1. Why move variables out of the inventory file

Remember what inventory/hosts.yml looks like right now: besides the hosts, it contains a vars: block under all. It works, but it has drawbacks:

Problem Consequence
It mixes structure and data To change a port you have to edit the file that defines which servers exist
It grows out of control Dozens of variables per group make the file unreadable
Changes are hard to review In git, every change touches the same file, and it's hard to see what changed and why
It can't be partially encrypted Later on you will want to encrypt secrets with Ansible Vault; it's much easier to do in a dedicated file
Limited INI format In INI, variables in [group:vars] are always strings

Ansible's solution is simple: one variables file per group and per host, in directories with well-known names that Ansible loads automatically.

  1. The group_vars/ and host_vars/ directories

Ansible looks for two special directories:

  • group_vars/<group>: variables for every host in that group.
  • host_vars/<host>: variables for a specific host.

The file name (without extension) must match exactly the name of the group or host in the inventory. Valid extensions are .yml, .yaml, .json or none at all.

Where does it look for them? In two places:

Location When it's loaded Recommended use
Next to the inventory source (in our case, inside inventory/) Whenever that inventory is used: with ansible, ansible-playbook, ansible-inventory… Environment-specific data: IPs, ports, versions
Next to the playbook being run Only with ansible-playbook Special cases; if it exists in both places, the playbook's one wins

For Aurora we settle on the first option: inventory/group_vars/ and inventory/host_vars/. That way variables always travel with their inventory, and once the staging and production environments exist, each one will have its own values with no risk of mixing them up.

inventory/
├── hosts.yml
├── group_vars/
│   ├── all/            ← variables for every host
│   ├── webservers.yml  ← variables for the webservers group
│   └── dbservers.yml   ← variables for the dbservers group
└── host_vars/
    ├── web1.yml        ← variables for web1 only
    ├── web2.yml
    └── db1.yml

  1. Standalone files or subdirectories

For each group or host you can use a file or a directory with several files inside:

group_vars/webservers.yml          # option A: a file

group_vars/all/                    # option B: a directory
├── connection.yml
└── aurora.yml

With a directory, Ansible loads every file it contains in alphabetical order and merges them. This is useful when a group has many variables and you want to split them by topic, or when some of them are secret: in Module 5 you will see the convention of putting encrypted secrets in a separate file (for example vault.yml) inside the same directory.

In Aurora we will use:

  • A directory for all, because it will hold variables of very different kinds (connection, general store data…).
  • A file for the remaining groups and for hosts, as long as they stay small.

Don't mix group_vars/all.yml and group_vars/all/ for the same group: it's confusing, and nobody will know where to look for a variable.

  1. Aurora Store's variables

Let's create the structure. From ~/aurora-infra:

mkdir -p inventory/group_vars/all inventory/host_vars

4.1 Cleaning up hosts.yml

Remove the vars: block from inventory/hosts.yml. Only the structure remains, with each host's address:

---
# Aurora Store lab inventory
all:
  children:
    aurora:                      # All of the store's servers
      children:
        webservers:              # Web servers (nginx)
          hosts:
            web1:
              ansible_host: 192.168.56.11
            web2:
              ansible_host: 192.168.56.12
        dbservers:               # Database servers (PostgreSQL)
          hosts:
            db1:
              ansible_host: 192.168.56.21

We keep ansible_host here because it's the information that identifies each machine: anyone reading hosts.yml should see at a glance which servers there are and where they are.

4.2 Shared variables: group_vars/all/

inventory/group_vars/all/connection.yml (what used to be under vars:):

---
# How to connect to the lab servers
ansible_user: vagrant
ansible_ssh_private_key_file: ~/.ssh/aurora_ed25519

inventory/group_vars/all/aurora.yml (general store data):

---
# General Aurora Store data
aurora_domain: aurora-store.example
aurora_env: lab
aurora_timezone: Europe/Madrid
aurora_admin_email: [email protected]
  • aurora_domain: the store's domain. It will be used by nginx, certificates, emails…
  • aurora_env: the environment the inventory belongs to (lab now; staging and production later on).
  • aurora_timezone: the time zone shared by all servers.
  • aurora_admin_email: the operations team's address.

Note the naming convention: the store's own variables start with aurora_, and those for a specific service start with the service name (nginx_, postgresql_). Prefixes avoid collisions and make it clear what each variable refers to. Ansible's special variables start with ansible_: never use that prefix for your own variables.

4.3 Group variables

inventory/group_vars/webservers.yml:

---
# Aurora Store web servers (nginx)
nginx_port: 80
nginx_worker_connections: 1024
aurora_web_root: /var/www/aurora

inventory/group_vars/dbservers.yml:

---
# Aurora Store database servers (PostgreSQL)
postgresql_version: 16
postgresql_port: 5432
postgresql_max_connections: 100
aurora_db_name: aurora
aurora_db_user: aurora
  • postgresql_version: 16 is the version Ubuntu 24.04 ships in its repositories.
  • Notice that nginx_port is the number 80, not the string "80": in YAML, types are preserved.

4.4 Host variables

inventory/host_vars/web1.yml:

---
# web1's weight in load balancing (it gets twice as much traffic)
aurora_lb_weight: 2

inventory/host_vars/web2.yml:

---
aurora_lb_weight: 1

inventory/host_vars/db1.yml:

---
# db1 has 2 GB of RAM: we reserve 25% for the PostgreSQL cache
postgresql_shared_buffers: 512MB

We won't use these variables to configure anything yet: you will do that with playbooks and templates in Modules 3 and 5. Right now the point is to have the data in the right place and check that Ansible can see it.

  1. Checking variables: ansible-inventory and the debug module

5.1 All of a host's variables

ansible-inventory -i inventory/ --host web1
{
    "ansible_host": "192.168.56.11",
    "ansible_ssh_private_key_file": "~/.ssh/aurora_ed25519",
    "ansible_user": "vagrant",
    "aurora_admin_email": "[email protected]",
    "aurora_domain": "aurora-store.example",
    "aurora_env": "lab",
    "aurora_lb_weight": 2,
    "aurora_timezone": "Europe/Madrid",
    "aurora_web_root": "/var/www/aurora",
    "nginx_port": 80,
    "nginx_worker_connections": 1024
}

This is the final view of web1: variables from all, from aurora (none), from webservers and from the host itself, already merged. Notice that the dbservers ones don't appear: web1 doesn't belong to that group.

5.2 The whole inventory

ansible-inventory -i inventory/ --list --yaml
ansible-inventory -i inventory/ --graph --vars

--graph --vars is very instructive: it shows each variable hanging from the group or host where it's defined, without merging.

5.3 Asking Ansible about a variable: ansible.builtin.debug

The ansible.builtin.debug module prints messages or variables. Unlike almost every other module, it doesn't run on the remote server: it's resolved on the control node, so it's instantaneous.

ansible aurora -i inventory/ -m ansible.builtin.debug -a var=aurora_domain
web1 | SUCCESS => {
    "aurora_domain": "aurora-store.example"
}
web2 | SUCCESS => { ... }
db1 | SUCCESS => { ... }

If a variable doesn't exist for a host, debug tells you so:

ansible aurora -i inventory/ -m ansible.builtin.debug -a var=nginx_port
web1 | SUCCESS => {
    "nginx_port": 80
}
web2 | SUCCESS => {
    "nginx_port": 80
}
db1 | SUCCESS => {
    "nginx_port": "VARIABLE IS NOT DEFINED!"
}

You can also build a message with the {{ }} template syntax (Jinja2, which you will study in depth in Module 5):

ansible webservers -i inventory/ -m ansible.builtin.debug \
  -a 'msg="{{ inventory_hostname }} serves {{ aurora_domain }} on port {{ nginx_port }}"'

inventory_hostname is a "magic" variable that Ansible always defines: the host's name in the inventory.

  1. Basic precedence: all, group and host

What happens if the same variable is defined in several places? Ansible applies precedence: each source has a level, and the highest level wins. For inventory variables the rule is intuitive: the more specific, the higher the priority.

graph LR
    A["group_vars/all"] --> B["parent group<br/>(aurora)"]
    B --> C["child group<br/>(webservers)"]
    C --> D["host_vars/web1"]
    style D fill:#d4edda

From lowest to highest priority:

Level Source Example
1 (lowest) Variables of the all group group_vars/all/aurora.yml
2 Variables of a parent group group_vars/aurora.yml
3 Variables of a child group group_vars/webservers.yml
4 (highest) Host variables host_vars/web1.yml

In addition, at the same level, files in group_vars//host_vars/ win over variables written inside the inventory file (vars: in hosts.yml).

Experiment

Define a temporary variable aurora_motd at three levels:

echo 'aurora_motd: "Aurora Store server"' >> inventory/group_vars/all/aurora.yml
echo 'aurora_motd: "Aurora Store web server"' >> inventory/group_vars/webservers.yml
echo 'aurora_motd: "web1: primary node"' >> inventory/host_vars/web1.yml

ansible aurora -i inventory/ -m ansible.builtin.debug -a var=aurora_motd
web1 | SUCCESS => { "aurora_motd": "web1: primary node" }
web2 | SUCCESS => { "aurora_motd": "Aurora Store web server" }
db1  | SUCCESS => { "aurora_motd": "Aurora Store server" }
  • web1 has the variable at host level: the host wins.
  • web2 has no host variable: its webservers group wins.
  • db1 isn't in webservers and has no host variable: it gets the one from all.

When you're done, remove those three lines from the files: it was only an experiment.

Variables don't add up, they replace each other. If all defines a list and webservers defines another one with the same name, a web host sees only the webservers one, not the union of both. The same applies to dictionaries (unless you change a configuration option, which isn't recommended).

A preview: full precedence

Inventory variables are only part of the story. Ansible has a total of 22 precedence levels, which also include role variables, playbook variables, facts, registered variables and extra vars (-e), which always win over everything else. You will study them in full in the "Variables and Facts" lesson in Module 3. For now, remember the rule "specific beats general" and that -e always wins.

  1. Ties between groups: depth, alphabetical order and ansible_group_priority

A host can be in several groups that aren't parent and child. If two of those groups define the same variable, which one wins? Ansible resolves it like this:

  1. Depth: a child group wins over its parent (it's more specific).
  2. Same level: groups are sorted alphabetically and the last one wins.
  3. ansible_group_priority: if defined, it changes the previous order. The default value is 1; the group with the highest number wins.

An example (don't add it to Aurora; it's just to understand the mechanism). Imagine that web2 is also in a canary group used to try out new versions:

# group_vars/webservers.yml
nginx_worker_connections: 1024

# group_vars/canary.yml
nginx_worker_connections: 2048

canary and webservers are at the same level (both children of aurora). Alphabetically, webservers comes after canary, so webservers wins (1024), probably the opposite of what you wanted. To make canary win, give it a higher priority in the inventory file itself:

# hosts.yml (excerpt, inside aurora.children)
        canary:
          hosts:
            web2:
          vars:
            ansible_group_priority: 10

ansible_group_priority is an exception to what you have learned in this lesson: it must be defined in the inventory source (hosts.yml), not in group_vars/, because Ansible needs it precisely to decide the order in which it applies group variables. Use it sparingly: if you need lots of priorities, your group structure is probably too complex.

  1. The open case: ansible_user versus -u

In Exercise 3 of lesson 1.5 you ran:

ansible web1 -i inventory.ini -m ansible.builtin.ping -u nonexistent_user

and, surprisingly, the result was SUCCESS. Now you have what you need to understand it:

  • The command-line -u option and the remote_user configuration setting are connection defaults.
  • ansible_user is an inventory connection variable, tied to the host (or its group).
  • In Ansible, inventory variables take priority over command-line connection options (-u, --private-key…) and over the configuration. The logic is that the inventory describes how to access that particular host, while -u is a general preference.
Source of the remote user Priority
remote_user in ansible.cfg Low
-u option on the command line Medium
ansible_user in the inventory (group_vars, host_vars, hosts.yml) High
-e ansible_user=... (extra vars) Highest

Check it:

# ansible_user (vagrant) wins: SUCCESS
ansible web1 -i inventory/ -m ansible.builtin.ping -u nonexistent_user

# Extra vars beat everything: UNREACHABLE (that user doesn't exist on web1)
ansible web1 -i inventory/ -m ansible.builtin.ping -e ansible_user=nonexistent_user

Is this a problem? It depends on where you want to define the user. In the next lesson, when we create ansible.cfg, we will revisit this decision: the lab's connection data will move into the configuration, and -u will behave as you expect again.

  1. Saving your work in git

git add inventory/
git commit -m "Inventory variables in group_vars and host_vars"

Current structure:

aurora-infra/
├── .gitignore
├── inventory/
│   ├── hosts.yml
│   ├── group_vars/
│   │   ├── all/
│   │   │   ├── aurora.yml
│   │   │   └── connection.yml
│   │   ├── dbservers.yml
│   │   └── webservers.yml
│   └── host_vars/
│       ├── db1.yml
│       ├── web1.yml
│       └── web2.yml
└── lab/
    └── Vagrantfile

Common Mistakes and Tips

  • The file name doesn't match the group or host: group_vars/webserver.yml (without the s) or host_vars/web1.aurora-store.example.yml when the host is called web1. Ansible doesn't warn you: it simply ignores the file. Always check with ansible-inventory --host.
  • group_vars/ in the wrong place: if you create it at the root of aurora-infra/ instead of inside inventory/, the ansible command won't load it (only playbooks located at that root would). Stick to the convention we've set.
  • Files with an unrecognized extension (webservers.yaml.bak, webservers.txt): they are ignored or, worse, loaded if they have no extension at all. Don't leave backup copies inside group_vars/.
  • Expecting lists to be merged: the most specific variable completely replaces the general one.
  • Using hyphens in variable names (nginx-port): they aren't valid in Jinja2. Use underscores.
  • Tip: document each variables file with an opening comment saying what it contains; your colleagues (and you, six months from now) will thank you.

Exercises

Exercise 1: A variable with an exception

Every Aurora server must have aurora_backup_enabled: true, except web2, which is an easily rebuildable server and doesn't need backups. Define the variable where it belongs and check the result with debug.

Exercise 2: Investigating without running anything remotely

Using only ansible-inventory, answer: what value does postgresql_max_connections have on db1? In which file is aurora_lb_weight defined for web2? Why doesn't web1 have postgresql_version?

Exercise 3: Predicting precedence

Assume these values for nginx_port: 8080 in group_vars/all/aurora.yml, 80 in group_vars/webservers.yml and 8081 in host_vars/web2.yml. What value does each host see? And if you run the command with -e nginx_port=9000?

Solutions

Exercise 1. A general value in all and an exception on the host:

echo 'aurora_backup_enabled: true' >> inventory/group_vars/all/aurora.yml
echo 'aurora_backup_enabled: false' >> inventory/host_vars/web2.yml
ansible aurora -i inventory/ -m ansible.builtin.debug -a var=aurora_backup_enabled

web1 and db1 show true; web2, false. Notice that these are YAML booleans (true/false without quotes). You can keep this variable: it fits Aurora's configuration.

Exercise 2.

ansible-inventory -i inventory/ --host db1        # postgresql_max_connections: 100
ansible-inventory -i inventory/ --graph --vars    # aurora_lb_weight hangs from web2 → host_vars/web2.yml

web1 doesn't have postgresql_version because it's only defined in group_vars/dbservers.yml, and web1 doesn't belong to dbservers.

Exercise 3. web1 sees 80 (the webservers group wins over all), web2 sees 8081 (its host variable wins) and db1 sees 8080 (only the all value reaches it). With -e nginx_port=9000, all three see 9000: extra vars have the highest precedence.

Conclusion

You have separated data from structure: inventory/hosts.yml describes which servers Aurora Store has, while inventory/group_vars/ and inventory/host_vars/ hold their variables, including the store's first configuration variables (aurora_domain, nginx_port, postgresql_version…). You know how to check them with ansible-inventory --host, --graph --vars and the debug module, you know the "specific wins" precedence rule and how ties between groups are resolved, and you understand why ansible_user was winning over -u. In the next lesson, Configuring Ansible (ansible.cfg), you will create the project's configuration file: you will set the default inventory so you never have to type -i again, move the connection data there and tailor Ansible's behavior to Aurora's needs.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved