Skip to main content

Infrastructure as code · Intermediate · 16 min

Organise Ansible variables with group_vars, host_vars and precedence

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0

You will lay out a staging and production Ansible inventory with values split across group_vars and host_vars, prove which of four competing settings wins, and leave with a rule for where each kind of value belongs.

On this page

A small Ansible project starts with one inventory file and a vars: block in the playbook. That holds until there are two environments, a database that needs different limits from the web servers, and one server you are debugging this week. Then the same setting appears in three places, and nobody is sure which one Ansible uses.

Ansible has a fixed answer to that question, its variable precedence order, and a directory layout that makes the answer easy to read: group_vars/ for values shared by a group, host_vars/ for values that belong to one machine. In this tutorial you build that layout for a staging and a production environment, inspect it with ansible-inventory, then set one variable at four levels and watch which value wins.

Nothing here logs in to a server. The plays use only the debug module with fact gathering turned off, so they run entirely on your control machine and you can follow along before the servers exist. The addresses in the inventories are documentation addresses; replace them with your own when you use the layout for real.

Step 1 · Install ansible-core and make a project folder

ansible-core is the engine and the built-in modules, which is all this tutorial needs. Install it with pipx, which gives it its own Python environment, and pin the version so your output matches:

Bash
sudo apt update
sudo apt install -y pipx openssh-client
pipx install ansible-core==2.22.0
export PATH="$HOME/.local/bin:$PATH"
mkdir -p ~/ansible-vars-demo
cd ~/ansible-vars-demo

Add the PATH line to ~/.bashrc (or run pipx ensurepath and open a new terminal) so the commands are found next time. A pipx install does not get updates from apt; upgrade it later with pipx upgrade ansible-core. The OpenSSH client is not used in this tutorial, but Ansible needs it as soon as you point these inventories at real servers.

Check it worked

Bash
ansible-inventory --version | head -n 1

The first line reads ansible-inventory [core 2.22.0].

Step 2 · Write one inventory per environment

Keep each environment in its own inventory file, in its own folder. A command then only touches the environment you name with -i, and staging values cannot leak into production by accident.

Create the production inventory. It holds the hosts, their groups and their addresses, and nothing else:

Bash
mkdir -p inventories/production inventories/staging
cat > inventories/production/hosts.yml <<'YAML'
all:
  children:
    web:
      hosts:
        web-prod-1:
          ansible_host: 203.0.113.11
        web-prod-2:
          ansible_host: 203.0.113.12
    db:
      hosts:
        db-prod-1:
          ansible_host: 203.0.113.21
YAML

Then the staging one, with the same groups and fewer machines:

Bash
cat > inventories/staging/hosts.yml <<'YAML'
all:
  children:
    web:
      hosts:
        web-stg-1:
          ansible_host: 198.51.100.11
    db:
      hosts:
        db-stg-1:
          ansible_host: 198.51.100.21
YAML

Using the same group names in both environments matters: a playbook that says hosts: web works against either inventory, and the environment is chosen only by the -i you pass.

Check it worked

Draw the production tree:

Bash
ansible-inventory -i inventories/production/hosts.yml --graph

You see @all at the top, @web with web-prod-1 and web-prod-2 under it, @db with db-prod-1, and an empty @ungrouped group that Ansible always adds. Run the same command with inventories/staging/hosts.yml and you see only the two staging hosts.

Step 3 · Put values every host shares in group_vars/all

Ansible looks for a group_vars/ folder next to the inventory file. A folder (or file) inside it named after a group applies to every host in that group, and all is the group every host belongs to. Use it for environment-wide values: the environment's name, the login user, time and logging settings.

Use a folder per group, group_vars/all/, rather than a single group_vars/all.yml file. Every .yml file in the folder is read, so you can split a large group into topic files later without moving anything.

Bash
mkdir -p inventories/production/group_vars/all
cat > inventories/production/group_vars/all/main.yml <<'YAML'
env_name: production
ansible_user: deploy
server_timezone: Africa/Lagos
ntp_servers:
  - 0.africa.pool.ntp.org
  - 1.africa.pool.ntp.org
max_open_files: 1024
app_log_level: warning
YAML

mkdir -p inventories/staging/group_vars/all
cat > inventories/staging/group_vars/all/main.yml <<'YAML'
env_name: staging
ansible_user: deploy
server_timezone: Africa/Lagos
ntp_servers:
  - 0.africa.pool.ntp.org
max_open_files: 1024
YAML

Replace the time zone and NTP pool with the ones for your region. africa.pool.ntp.org is the NTP Pool's zone for the continent; servers in the same region answer with less delay, which helps on links where every round trip is slow. Notice that staging does not set app_log_level. That gap is deliberate, and you will see what fills it later.

Check it worked

Bash
ansible-inventory -i inventories/production/hosts.yml --graph --vars | grep 'env_name = production'

--vars adds each variable to the tree as {name = value}, so the line {env_name = production} appears in the output. Run the command without the grep to see the whole tree with its values.

Step 4 · Give each group its own folder of values

Web servers and database servers need different settings. Each gets a folder under group_vars/. Split the web group into two files, one for the application and one for Nginx, to see how a folder keeps a growing group readable:

Bash
mkdir -p inventories/production/group_vars/web inventories/production/group_vars/db
cat > inventories/production/group_vars/web/app.yml <<'YAML'
app_port: 8080
app_workers: 4
YAML
cat > inventories/production/group_vars/web/nginx.yml <<'YAML'
nginx_worker_connections: 2048
nginx_client_max_body_size: 20m
YAML
cat > inventories/production/group_vars/db/main.yml <<'YAML'
db_port: 5432
db_max_connections: 200
max_open_files: 65536
YAML

Do the same for staging, with smaller numbers:

Bash
mkdir -p inventories/staging/group_vars/web inventories/staging/group_vars/db
cat > inventories/staging/group_vars/web/app.yml <<'YAML'
app_port: 8080
app_workers: 1
YAML
cat > inventories/staging/group_vars/web/nginx.yml <<'YAML'
nginx_worker_connections: 512
nginx_client_max_body_size: 20m
YAML
cat > inventories/staging/group_vars/db/main.yml <<'YAML'
db_port: 5432
db_max_connections: 50
max_open_files: 65536
YAML

Files inside one group folder are read in alphabetical order, so if app.yml and nginx.yml both set the same name, nginx.yml wins. Avoid relying on that: give each variable one home.

max_open_files is now set twice for the database host, at 1024 in all and 65536 in db. Inside an inventory, the more specific group wins: all is read first, then the groups beneath it, then the host itself.

Check it worked

--host prints the merged result for one machine, after every group has been applied:

Bash
ansible-inventory -i inventories/production/hosts.yml --host db-prod-1 | grep max_open_files
ansible-inventory -i inventories/production/hosts.yml --host web-prod-1 | grep max_open_files

The database host shows "max_open_files": 65536 and the web host shows "max_open_files": 1024. Run --host web-prod-1 without the grep to see every value it receives, including app_port and the two Nginx settings.

Step 5 · Override one machine with host_vars

Sometimes one server needs to differ from its group: a canary that gets releases first, or a host you are debugging. That value goes in host_vars/<hostname>.yml, next to the inventory. Here web-prod-2 gets verbose logging while you chase a problem on it:

Bash
mkdir -p inventories/production/host_vars
cat > inventories/production/host_vars/web-prod-2.yml <<'YAML'
# Debugging a slow request on this host. Remove when done.
app_log_level: debug
canary: true
YAML

The comment is worth the line. A host override that nobody remembers is how one server ends up behaving differently from the others for a year.

Check it worked

Bash
ansible-inventory -i inventories/production/hosts.yml --host web-prod-2 | grep app_log_level
ansible-inventory -i inventories/production/hosts.yml --host web-prod-1 | grep app_log_level

web-prod-2 shows "app_log_level": "debug" from its host file, and web-prod-1 still shows "app_log_level": "warning" from group_vars/all. Your production folder now looks like this:

Text
inventories/production/
├── hosts.yml
├── group_vars/
│   ├── all/main.yml
│   ├── db/main.yml
│   └── web/
│       ├── app.yml
│       └── nginx.yml
└── host_vars/
    └── web-prod-2.yml

Step 6 · Set one variable at four levels and see which wins

Inventory is only one layer. Variables can also come from a role's defaults, a play's vars: block and the command line. Ansible's documented order, lowest to highest, for the places you will use most is:

  1. Role defaults (roles/<role>/defaults/main.yml)
  2. Inventory: group_vars/all, then other groups, then host_vars
  3. Play vars: in the playbook
  4. Extra vars on the command line (-e), which always win

Build a small role whose default log level is info, and a playbook that prints what each host ends up with. gather_facts: false stops Ansible logging in to collect facts, and ansible.builtin.debug runs on the control machine, so nothing contacts the servers:

Bash
mkdir -p roles/report/defaults roles/report/tasks
cat > roles/report/defaults/main.yml <<'YAML'
app_log_level: info
YAML
cat > roles/report/tasks/main.yml <<'YAML'
- name: Show the value this host receives
  ansible.builtin.debug:
    msg: "{{ inventory_hostname }} env={{ env_name }} log_level={{ app_log_level }}"
YAML
cat > site.yml <<'YAML'
- name: Report variables
  hosts: all
  gather_facts: false
  roles:
    - report
YAML

The playbook sits at the project root, away from the inventories/ folders. That is on purpose: Ansible also reads group_vars/ and host_vars/ next to the playbook, with a higher precedence than the ones next to the inventory, and a second set there makes the layout harder to reason about.

Run it against both environments:

Bash
ansible-playbook -i inventories/production/hosts.yml site.yml | grep 'log_level='
ansible-playbook -i inventories/staging/hosts.yml site.yml | grep 'log_level='

Production prints log_level=warning for web-prod-1 and db-prod-1, and log_level=debug for web-prod-2. Staging prints log_level=info for both hosts: its inventory never sets the variable, so the role default fills the gap. That is what role defaults are for, a sensible value that any inventory can replace.

Now add a play vars: block, as people often do when they want "just this one value" in the playbook:

Bash
cat > site.yml <<'YAML'
- name: Report variables
  hosts: all
  gather_facts: false
  vars:
    app_log_level: error
  roles:
    - report
YAML
ansible-playbook -i inventories/production/hosts.yml site.yml | grep 'log_level='

Every host now prints log_level=error, including web-prod-2. Play vars outrank the whole inventory, so the host override you set on purpose has silently stopped working. Put the playbook back the way it was:

Bash
cat > site.yml <<'YAML'
- name: Report variables
  hosts: all
  gather_facts: false
  roles:
    - report
YAML

Finally, pass the value on the command line, as you would for a one-off run:

Bash
ansible-playbook -i inventories/production/hosts.yml site.yml -e app_log_level=critical | grep 'log_level='

Every host prints log_level=critical. Extra vars beat everything, including values set later in the play, which makes them right for a single run you are watching and wrong for anything that should be repeatable.

One more level is worth knowing even though you did not use it: a role's vars/main.yml sits above play vars and above the inventory. Put a value there only if no inventory should ever change it; otherwise use defaults/.

Check it worked

Bash
ansible-playbook -i inventories/production/hosts.yml site.yml | grep 'log_level=debug'

One line comes back, for web-prod-2. With the vars: block gone and no -e, the inventory decides again, and the host override works as intended.

Step 7 · Decide where each value goes, then tidy up

The layout and the precedence order together give a short rule:

  • Connection details (ansible_host, and ansible_port if it differs) go next to the host in hosts.yml. Nothing else goes there. Group variables written inside the inventory file rank below group_vars/, and host variables written there rank above every group_vars/ file and below host_vars/. Keeping values out of hosts.yml means a reader never has to remember either rule.
  • Environment-wide values (environment name, login user, time zone, logging) go in group_vars/all/.
  • Values for one kind of server go in group_vars/<group>/, split into topic files when the group grows.
  • Values for one machine go in host_vars/<host>.yml, with a comment saying why, and are removed when the reason ends.
  • A role's working defaults go in the role's defaults/main.yml, so any inventory can override them.
  • Extra vars (-e) are for one-off runs you are watching. If you pass the same -e twice, it belongs in the inventory.
  • Play vars: are for values that never vary by environment or host. If you are tempted to put an environment-specific value there, it belongs in group_vars/.
  • Secrets do not go in any of these as plain text. Keep them in files encrypted with Ansible Vault, inside the same group_vars/ folders, as shown in /tutorials/encrypt-secrets-with-ansible-vault.

Before you hand the layout to a team, check that each variable has one home per environment:

Bash
grep -rn '^app_log_level:' inventories/production roles

The pattern matches only lines that set the variable, not the place the role uses it, so you see three definitions, each with a clear job: the role default, the production value in group_vars/all, and the host override for web-prod-2. If a variable appears in two files at the same level, pick one and delete the other.

When you are finished, remove the demo project. This deletes only the folder this tutorial created:

Bash
cd ~
rm -rf ~/ansible-vars-demo

Run pipx uninstall ansible-core too if you do not need Ansible on this machine.

Check it worked

Bash
test ! -e ~/ansible-vars-demo && echo "demo folder removed"

It prints demo folder removed.

Next steps

  • Use these inventories against real servers with a full playbook: /tutorials/configure-a-server-with-an-ansible-playbook.
  • Move the report idea into proper roles with their own defaults: /tutorials/organise-ansible-work-into-roles.
  • Check roles automatically before they reach any inventory: /tutorials/test-ansible-roles-with-ansible-lint-and-molecule.
  • Keep passwords and keys in these group_vars/ folders safely: /tutorials/encrypt-secrets-with-ansible-vault.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.