Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

โ€œInvest in yourself โ€” your confidence is always worth it.โ€

Explore Cosmetic Hospitals

Start your journey today โ€” compare options in one place.

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.

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
Iโ€™m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Terraform Backend Tutorial

Terraform is a popular open-source infrastructure as code tool used to create and manage infrastructure resources. The state of the infrastructure resources managed by Terraform is stored…

Read More

Best Tools for Software Composition Analysis (SCA)

Hereโ€™s a clear and professional explanation of the three related concepts you asked about โ€” all of which are critical parts of secure software development, especially in…

Read More

Top 10 AI Code Review Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, AI code review tools have become essential for developers aiming to enhance code quality, streamline workflows, and accelerate software delivery. These tools leverage advanced…

Read More

Top 10 Expense Management Tools in 2026: Features, Pros, Cons & Comparison

Introduction Expense management tools are critical for businesses of all sizes in 2026 as they help streamline financial processes, improve budgeting, ensure compliance, and enhance financial visibility….

Read More

Top 10 Web Application Firewall (WAF) Tools in 2026: Features, Pros, Cons & Comparison

Introduction In the rapidly evolving landscape of cybersecurity, Web Application Firewalls (WAFs) have become a critical component in defending web applications from malicious attacks such as SQL…

Read More

Top 10 Endpoint Management Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, businesses of all sizes are increasingly reliant on a variety of devicesโ€”laptops, desktops, mobile devices, and other endpointsโ€”that connect to their networks. With the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x