What it says on the tin: the group_vars
directory contains variable definitions for inventory groups.
This is a way to scope variables to a given inventory group.
We can define variables for the elasticsearch inventory group
that are not accessible by plays running on the application inventory group.
Ansible expects the following directory structure:
group_vars/
group_vars/<inventory_group>.yml
OR
grou_vars/
group_vars/<inventory_group>/*.yml
Within the group_vars/<inventory_group>/ sub-directory,
Ansible loads variable definitions from all
⚠️ CAUTION:group_varsare very far down the variable precedence order. Role variables (not defaults) will override them. See Appendix: Variable precedence
So a variable defined in group_vars/all/config.yml is accessible by
all plays running on any inventory group (because it is scoped to all).
So, with group_vars/elasticsearch/asdf.yml:
# group_vars/elasticsearch/asdf.yml
---
my_test_var: "test"We can run the following play:
# Test playbook
- name: test
hosts: elasticsearch
gather_facts: false
tasks:
- name: Debug
ansible.builtin.debug:
msg: |
{{ my_test_var }}But the following fails to find the my_test_var variable:
# Test playbook
- name: test
hosts: application
gather_facts: false
tasks:
- name: Debug
ansible.builtin.debug:
msg: |
{{ my_test_var }}Running the same against the all implicit inventory group
passes for managed nodes in the elasticsearch inventory group,
but fails on all others.
📘 NOTE:
localhostis not an implicit or default inventory group. It is an implicit host (see implicit localhost).
Ansible does apply variable precedence, and you might have a use for it. Here is the order of precedence from least to greatest (the last listed variables override all other variables):
- Command-line values (for example, -u my_user, these are not variables)
- Role defaults (as defined in Role directory structure)
- Inventory file or script group vars
- Inventory group_vars/all
- Playbook group_vars/all
- Inventory group_vars/*
- Playbook group_vars/*
- Inventory file or script host vars
- Inventory host_vars/*
- Playbook host_vars/*
- Host facts and cached set_facts
- Play vars
- Play vars_prompt
- Play vars_files
- Role vars (as defined in Role directory structure)
- Block vars (for tasks in block only)
- Task vars (for the task only)
- include_vars
- Registered vars and set_facts
- Role (and include_role) params
- include params
- Extra vars (for example, -e "user=my_user")(always win precedence)