Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOpsSchool!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Ansible: All Ways to Define Variables in Ansible Inventory/Hosts

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):

  1. Extra vars (-e)
  2. Task/block vars
  3. Role vars
  4. Play vars
  5. Host vars (from host_vars/ or inventory)
  6. Group vars (from group_vars/ or inventory)
  7. All group vars ([all:vars] or group_vars/all.yml)
  8. Playbook/inventory defaults
  9. Facts

See Ansible docs: Variable precedence


Quick Reference Table

MethodExample Syntax / PathScopeExample Value
Host vars in INIweb1 ansible_host=1.2.3.4One hostweb1 ansible_host=1.2.3.4
Group vars in INI[group:vars] key=valueAll group hosts[web:vars] port=80
All group vars[all:vars] key=valueAll hosts[all:vars] env=prod
YAML inventory varsvars: blockAny host/groupvars: {foo: bar}
group_vars/ dirgroup_vars/webservers.ymlAll group hostsnginx_version: 1.24
host_vars/ dirhost_vars/web1.ymlOne hosthttp_port: 8080
Playbook varsvars: in playAll play hostsvars: {debug: true}
Extra vars-e "foo=bar"All play hostsCLI only
Dynamic inventory JSONhostvars/vars keysFrom dynamic sourceAWS, GCP plugins, etc.
Environment vars (lookup)lookup('env', 'VAR')Local to playbooke.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/ and host_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.

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x