Lesson 12 / 26
group_vars and host_vars
Store variables per group and per host in a clean directory layout.
Variables next to the inventory
Instead of cramming variables into the inventory file, create group_vars/<group>.yml and host_vars/<host>.yml beside it. Ansible loads them automatically. Variables in group_vars/all.yml apply everywhere, while group_vars/web.yml applies to the web group and host_vars/web1.yml only to that host. This keeps data separate from logic and makes environment differences easy to see in code review.
A typical layout
Environment-specific values live in the inventory directory of that environment.
inventories/
staging/
hosts.ini
group_vars/
all.yml # app_env: staging
web.yml # http_port: 8080
production/
hosts.ini
group_vars/
all.yml # app_env: production
web.yml # http_port: 80
playbooks/site.yml
roles/...One playbook, many environments
Run ansible-playbook -i inventories/staging site.yml and later -i inventories/production. The playbook stays identical; only the data changes.
Quick check: Where do you put variables that apply only to the web group?
- ansible.cfg only
- group_vars/web.yml
- A random hosts file
- A comment in the playbook
Answer
group_vars/web.yml — Ansible loads group_vars/<group>.yml automatically for hosts in that group.