Ansible group_vars & host_vars: Organize Variables by Host and Group
By Luca Berton · Published 2024-01-01 · Category: linux-administration
Complete guide to Ansible group_vars and host_vars directories. Organize variables by group and host, use vault-encrypted files, understand variable precedence, and structure multi-environment inventories with practical examples.
group_vars and host_vars are directories where you store variables for groups and individual hosts. They keep your inventory clean and your variables organized by environment, role, or host.
Directory Structure
group_vars: Variables by Group
host_vars: Variables by Host
Using Variables in Playbooks
Directory Format (Multiple Files)
Split variables into multiple files per group:
Multi-Environment Setup
Variable Precedence
From lowest to highest priority:
group_vars/all (lowest)
group_vars/
hostvars: Access Other Host's Variables
Vault-Encrypted Variables
Best practice — reference vault variables with a vault_ prefix:
Practical Examples
Complete Project Structure
Dynamic Variables per Environment
FAQ
Where should I put group_vars — next to inventory or playbook?
Both locations work. Ansible checks group_vars/ next to the inventory file AND next to the playbook. For multi-environment setups, keep them with the inventory. For single-inventory projects, put them at the project root.
Can I use subdirectories inside group_vars?
Yes. group_vars/webservers/ (a directory) works the same as group_vars/webservers.yml (a file). All YAML files in the directory are loaded and merged. Use directories when you want to separate vault files from plain vars.
How do I set variables for a child group?
If webservers is a child of linux, variables in group_vars/linux.yml apply to webservers too. Child group vars override parent group vars.
What's the difference between hostvars and host_vars?
host_vars/ is a directory for storing per-host variable files. hostvars is a runtime variable in Ansible that lets you access any host's variables during playbook execution: hostvars['hostname'].variable_name.
Conclusion
Use group_vars/all.yml for shared defaults, group_vars/
Related Articles • Ansible Inventory Guide • Ansible Vault Deep Dive • Ansible set_fact vs vars vs extra_vars • Ansible gather_facts Guide
Category: linux-administration