TExcelTAD
Home › Configuration Management: Ansible › Groups, host_vars & group_vars

Groups, host_vars & group_vars

Writing variables after each host in the inventory file stops being readable at the third variable. Ansible looks for two folders next to the inventory (and next to the playbook) instead:

text
inventory/
├── hosts.ini
├── group_vars/
│   ├── all.yml            # every host
│   ├── web.yml            # hosts in group web
│   └── prod/              # a folder works too: every file in it is read
│       ├── main.yml
│       └── vault.yml      # encrypted secrets, see the Vault lesson
└── host_vars/
    └── web2.yml           # only web2

The file name (without .yml/.yaml/.json) is the group or host name. Keep the inventory file for which hosts exist, and these folders for how they differ.

Which value wins

A host usually gets the same variable from several places. Inside the inventory, the order from weakest to strongest is:

  1. all group variables
  2. parent group variables (prod)
  3. child group variables (web), the deeper the stronger
  4. host variables

Groups at the same depth are merged alphabetically, so a later group name wins. You can override that with ansible_group_priority (a higher number wins; it can only be set in the inventory itself, not in group_vars). The full precedence list (22 levels, from role defaults to -e) is in Variable Precedence.

bash · try it yourself
mkdir -p inv/group_vars inv/host_vars
cat > inv/hosts.ini <<'INI'
[web]
web1
web2

[db]
db1

[prod:children]
web
db
INI
cat > inv/group_vars/all.yml <<'YML'
ansible_connection: local
ntp_server: pool.ntp.org
http_port: 80
log_level: info
YML
cat > inv/group_vars/prod.yml <<'YML'
ntp_server: ntp.corp.example
log_level: warning
YML
cat > inv/group_vars/web.yml <<'YML'
http_port: 8080
YML
cat > inv/host_vars/web2.yml <<'YML'
log_level: debug
YML
for h in web1 web2 db1; do
  echo "== $h"
  ansible-inventory -i inv/hosts.ini --host "$h" | jq -c '{ntp_server, http_port, log_level}'
done
== web1
{"ntp_server":"ntp.corp.example","http_port":8080,"log_level":"warning"}
== web2
{"ntp_server":"ntp.corp.example","http_port":8080,"log_level":"debug"}
== db1
{"ntp_server":"ntp.corp.example","http_port":80,"log_level":"warning"}

Read the result row by row:

  • ntp_server: all says pool.ntp.org, prod (more specific) overrides it for every host.
  • http_port: only the web hosts get 8080; db1 keeps the all default.
  • log_level: prod sets warning, but the host file for web2 wins with debug.

Same-depth groups and ansible_group_priority

A host in two sibling groups gets the value from the group whose name sorts last:

bash · try it yourself
mkdir -p inv/group_vars
cat > inv/hosts.ini <<'INI'
[app]
node1 ansible_connection=local

[blue]
node1
INI
echo "color: from-app" > inv/group_vars/app.yml
echo "color: from-blue" > inv/group_vars/blue.yml
ansible-inventory -i inv/hosts.ini --host node1 | jq -r .color
# now make app stronger
cat > inv/hosts.ini <<'INI'
[app]
node1 ansible_connection=local

[app:vars]
ansible_group_priority=10

[blue]
node1
INI
ansible-inventory -i inv/hosts.ini --host node1 | jq -r .color
from-blue
from-app

Relying on alphabetical order is fragile: renaming a group silently changes values. If two groups at the same depth set the same variable, that is usually a design smell; give one variable one owner.

Variables you can see from other hosts

Every host's variables are available to every play through hostvars: hostvars['db1'].ansible_host gives a web server the database's address. Groups are in groups: groups['web'] is the list of web hosts, which is how a load balancer config lists its back ends. The templates lesson uses both.

bash · try it yourself
cat > hosts.ini <<'INI'
[web]
web1 ansible_connection=local backend_port=8080
web2 ansible_connection=local backend_port=8081

[lb]
lb1 ansible_connection=local
INI
cat > show.yml <<'YML'
- name: What the load balancer can see
  hosts: lb
  gather_facts: false
  tasks:
    - name: List the back ends
      ansible.builtin.debug:
        msg: "{{ item }} on port {{ hostvars[item].backend_port }}"
      loop: "{{ groups['web'] }}"
YML
ansible-playbook -i hosts.ini show.yml

PLAY [What the load balancer can see] ******************************************

TASK [List the back ends] ******************************************************
ok: [lb1] => (item=web1) => {
    "msg": "web1 on port 8080"
}
ok: [lb1] => (item=web2) => {
    "msg": "web2 on port 8081"
}

PLAY RECAP *********************************************************************
lb1                        : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Test yourself

group_vars/all.yml sets port: 80, group_vars/web.yml sets port: 8080, host_vars/web1.yml sets port: 9000. What does web1 (in group web) get?

  1. 80
  2. 8080
  3. 9000
  4. An error

A host is in sibling groups alpha and beta, both setting x, with no ansible_group_priority. Which value wins?

  1. alpha's
  2. beta's (the name that sorts last)
  3. Ansible fails
  4. It is random

How does a play on the load balancer read a variable of web1?

  1. web1.var
  2. hostvars['web1'].var
  3. groups.web1.var
  4. It can't