Here’s a comprehensive tutorial on all the ways to define and use variables in Ansible inventory/hosts, covering every major approach—including their best use cases and clear examples for each.
Complete Guide: All Ways to Define Variables in Ansible Inventory/Hosts
Ansible variables make playbooks and roles flexible and dynamic. Variables can be defined in multiple ways, with different precedence and scopes: per host, per group, globally, in YAML, in INI, or in directory structures.
Below, we’ll cover every method with examples.
1. Host Variables in Inventory File (Host Vars)
Define variables directly for a single host in the INI inventory file:
[webservers]
web1 ansible_host=192.168.1.101 http_port=80 max_clients=200
web2 ansible_host=192.168.1.102 http_port=8080 max_clients=150
Usage in playbook/task:
- name: Show host vars
hosts: webservers
tasks:
- debug: msg="Host {{ inventory_hostname }} uses port {{ http_port }} and max clients {{ max_clients }}"
Code language: JavaScript (javascript)
2. Group Variables in Inventory File (Group Vars)
Define variables for all hosts in a group in the INI inventory:
[dbservers]
db1 ansible_host=192.168.1.201
db2 ansible_host=192.168.1.202
[dbservers:vars]
db_port=3306 backup_window=02:00
All hosts in [dbservers]
get db_port
and backup_window
.
3. Global (All) Group Vars
Set variables for all hosts by using the [all:vars]
section in your INI inventory:
[all:vars]
env=production
admin_email=admin@example.com
All hosts will inherit these.
4. Using YAML Inventory (hosts.yml
)
YAML-style inventory files let you define hosts, groups, and variables in a structured way:
all:
vars:
datacenter: DC1
children:
webservers:
hosts:
web1:
ansible_host: 192.168.1.101
http_port: 80
web2:
ansible_host: 192.168.1.102
http_port: 8080
vars:
nginx_version: 1.24
dbservers:
hosts:
db1:
db2:
vars:
db_port: 3306
Code language: CSS (css)
Usage in playbook: Variables are accessed as usual ({{ db_port }}
etc).
5. Host and Group Variable Files (host_vars
& group_vars
Directory)
This is the most powerful and recommended way for larger projects.
Directory structure:
inventory/
hosts # inventory file (can be INI or YAML)
group_vars/
all.yml # applies to all hosts
webservers.yml
dbservers.yml
host_vars/
web1.yml
db1.yml
Code language: PHP (php)
Example:
inventory/group_vars/webservers.yml
:http_port: 80 nginx_version: 1.23
inventory/host_vars/web1.yml
:http_port: 8080
All hosts in webservers get http_port=80, except web1 (overrides to 8080).
6. Nested Groups and Variables (children
keyword in YAML)
You can nest groups, with vars defined for parent or child groups:
all:
children:
frontend:
hosts:
web1:
web2:
vars:
tier: frontend
backend:
hosts:
db1:
db2:
vars:
tier: backend
vars:
env: production
7. Dynamic Inventory with Variables
Dynamic inventory scripts/plugins (e.g., for AWS) can return host/group variables as part of their JSON:
{
"webservers": {
"hosts": ["web1", "web2"],
"vars": {
"http_port": 80
}
},
"_meta": {
"hostvars": {
"web1": {"nginx_version": "1.24"},
"web2": {"nginx_version": "1.22"}
}
}
}
Code language: JSON / JSON with Comments (json)
8. Using vars
in Playbooks, Roles, and Tasks
You can define variables directly in a playbook, though these are not inventory variables:
- hosts: webservers
vars:
http_port: 8080
max_clients: 100
tasks:
- debug: msg="Port is {{ http_port }}"
Code language: JavaScript (javascript)
- Note: These override inventory vars (except for host_vars and group_vars, which have higher precedence).
9. Extra Vars (-e
) at Command Line
Highest precedence!
ansible-playbook -i inventory/hosts site.yml -e "env=staging http_port=8081"
Code language: JavaScript (javascript)
10. Environment Variables
You can access environment variables with lookup('env', 'ENV_VAR_NAME')
in your playbooks.
These are not inventory vars, but often used for secrets.
11. Facts as Variables
Ansible facts (collected via setup
module) are accessible as variables (e.g. ansible_hostname
, ansible_distribution
).
Precedence: Which Variables Override Which?
(Highest to lowest):
- Extra vars (
-e
) - Task/block vars
- Role vars
- Play vars
- Host vars (from
host_vars/
or inventory) - Group vars (from
group_vars/
or inventory) - All group vars (
[all:vars]
orgroup_vars/all.yml
) - Playbook/inventory defaults
- Facts
See Ansible docs: Variable precedence
Quick Reference Table
Method | Example Syntax / Path | Scope | Example Value |
---|---|---|---|
Host vars in INI | web1 ansible_host=1.2.3.4 | One host | web1 ansible_host=1.2.3.4 |
Group vars in INI | [group:vars] key=value | All group hosts | [web:vars] port=80 |
All group vars | [all:vars] key=value | All hosts | [all:vars] env=prod |
YAML inventory vars | vars: block | Any host/group | vars: {foo: bar} |
group_vars/ dir | group_vars/webservers.yml | All group hosts | nginx_version: 1.24 |
host_vars/ dir | host_vars/web1.yml | One host | http_port: 8080 |
Playbook vars | vars: in play | All play hosts | vars: {debug: true} |
Extra vars | -e "foo=bar" | All play hosts | CLI only |
Dynamic inventory JSON | hostvars /vars keys | From dynamic source | AWS, GCP plugins, etc. |
Environment vars (lookup) | lookup('env', 'VAR') | Local to playbook | e.g. AWS keys |
Examples:
A. group_vars/webservers.yml
nginx_version: 1.25
Code language: CSS (css)
B. host_vars/web1.yml
http_port: 8088
Code language: HTTP (http)
C. INI Inventory with Group Vars
[appservers]
app1 ansible_host=1.2.3.10
app2 ansible_host=1.2.3.11
[appservers:vars]
app_env=staging
D. YAML Inventory with Group/Host Vars
all:
children:
monitoring:
hosts:
zabbix1:
zabbix_agent_port: 10050
E. Dynamic Inventory
Returned by AWS/GCP inventory plugins, includes host/group vars.
Summary
- Host vars: Specific to one host, defined in inventory,
host_vars/
, or dynamic inventory. - Group vars: For a whole group, defined in inventory,
group_vars/
, or dynamic inventory. - All group vars: Apply to all hosts.
- YAML inventory: Clean, scalable, supports all of the above.
- Directory structure (
group_vars/
,host_vars/
): Recommended for big projects. - Extra vars: For overrides and quick changes.
- Dynamic inventory: Great for cloud, VMs, auto-scaling.
- Precedence matters! The closer to the CLI, the more powerful.
Best Practice
- Use
group_vars/
andhost_vars/
directories for maintainable, scalable automation. - For dynamic environments (cloud), use dynamic inventory + host/group vars returned as JSON.
- Reserve extra vars (
-e
) for CI/CD or special cases.
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at Cotocus. I share tech blog at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow , and SEO strategies at Wizbrand.
Do you want to learn Quantum Computing?
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at WIZBRAND