Variables are what make Ansible playbooks reusable instead of disposable. Without them, you end up hardcoding hostnames, ports, and package names into every task, and any change means rewriting half your automation. With variables, the same playbook deploys to staging and production by swapping a single file.
This guide covers every variable type you’ll use in practice: facts gathered from remote hosts, custom variables in playbooks and files, group and host-level overrides, registered output, set_fact for runtime decisions, filters for data transformation, and the precedence rules that decide which value wins when the same name is defined in several places. If you need the basics first, start with the Ansible playbook tutorial. Every example below was re-run on ansible-core 2.22.0 in November 2026, on a Rocky Linux 10.2 controller running Python 3.14, which also served as the Rocky managed host next to an Ubuntu 26.04 one, and every output block comes from that run.
Prerequisites
You need the following before starting:
- Ansible installed on a control node. See how to install Ansible on Rocky Linux and Ubuntu if needed
- Python 3.13 or newer on the controller, because the current ansible-core release refuses older interpreters (we used the
python3.14package from Rocky 10.2 AppStream in a venv) - At least one managed host reachable over SSH with a sudo-capable user
- Familiarity with Ansible inventory and basic YAML syntax
The Python floor is the one that catches people on Ubuntu 24.04 and Rocky 10, whose default python3 is 3.12, so pip there quietly resolves an older ansible-core. Our guide to install Ansible on Rocky Linux and Ubuntu covers the venv setup that gets you the current core.
The project structure we’ll build throughout this guide keeps every playbook in the project root, so relative paths like vars/app_config.yml resolve without surprises:
ansible-lab/
├── ansible.cfg
├── inventory.ini
├── group_vars/
│ ├── all/main.yml
│ ├── rocky/main.yml
│ └── ubuntu/main.yml
├── host_vars/
│ ├── rocky-managed/main.yml
│ └── ubuntu-managed/main.yml
├── roles/
│ └── demo/
├── vars/
│ ├── app_config.yml
│ └── secrets.yml
└── *.yml (playbooks)
Create the inventory first. The group names matter, because Ansible matches group_vars directories to them by name, so a typo here means a whole directory of variables never loads. We use short aliases instead of raw IPs for the same reason: the alias is what host_vars directories are named after.
vim inventory.ini
You get two hosts, one group per OS, and a webservers parent group that contains both.
[rocky]
rocky-managed ansible_host=10.0.1.11 ansible_user=josphat
[ubuntu]
ubuntu-managed ansible_host=10.0.1.12 ansible_user=josphat
[webservers:children]
rocky
ubuntu
Then point Ansible at it in a project-level config file, so you never have to pass -i on the command line. Ansible reads ansible.cfg from the current directory first, which is why every command in this guide runs from the project root.
vim ansible.cfg
The auto_silent setting keeps the interpreter discovery warning out of every run, which matters here because you will be reading a lot of output.
[defaults]
inventory = inventory.ini
host_key_checking = False
interpreter_python = auto_silent
A quick version check and ping confirms the controller runs the new core and both managed hosts answer. Both discovered /usr/bin/python3.14. Ubuntu 26.04 ships it by default, and in our lab the Rocky managed host is the controller itself, where we had installed the AppStream package. A stock Rocky 10.2 managed host discovers its default Python 3.12 instead, which is fine, because the 3.13 floor applies to the controller only:

If the ping fails at this point, fix SSH before going further. Every variable example below depends on Ansible reaching both hosts.
Ansible Facts: Variables Gathered from Remote Hosts
Every time a playbook runs, Ansible connects to each host and collects system information automatically. These are called facts: the OS name, IP address, memory, CPU count, kernel version, and dozens more. Facts are available as variables inside your playbook without any extra work, but they are not free, because the Gathering Facts task runs the setup module on every host before your first task. On a play that never reads a fact, set gather_facts: false and you skip that round trip entirely, which we do in the precedence probe later.
Query facts for a specific host with the setup module. To filter for distribution-related facts only:
ansible rocky-managed -m setup -a "filter=ansible_distribution*"
On Rocky Linux 10.2, the list now includes ansible_distribution_cpe_name, a fact that is new in this ansible-core release:
rocky-managed | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "Rocky",
"ansible_distribution_cpe_name": "cpe:/o:rocky:rocky:10::baseos",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/redhat-release",
"ansible_distribution_file_variety": "RedHat",
"ansible_distribution_major_version": "10",
"ansible_distribution_release": "Red Quartz",
"ansible_distribution_version": "10.2",
"discovered_interpreter_python": "/usr/bin/python3.14"
},
"changed": false
}
The same command on Ubuntu 26.04 shows different values, and one of them is worth a second look:
ubuntu-managed | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "Ubuntu",
"ansible_distribution_cpe_name": null,
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/os-release",
"ansible_distribution_file_variety": "Debian",
"ansible_distribution_major_version": "26",
"ansible_distribution_release": "resolute",
"ansible_distribution_version": "26.04",
"discovered_interpreter_python": "/usr/bin/python3.14"
},
"changed": false
}
The CPE fact comes straight from the CPE_NAME line in /etc/os-release, and Ubuntu doesn’t publish one, so the fact is null there. That’s the trap with it: a compliance task that keys off the CPE string works on the RHEL family and silently gets nothing on Ubuntu. Guard it with default() or a when: ansible_facts['distribution_cpe_name'] check. For branching by platform, ansible_distribution and ansible_os_family are still the reliable keys, and the full value list per distro is in our Ansible os_family and distribution facts reference.

Both hosts side by side make the gap obvious: same playbook, same fact name, one real value and one null.
The ansible_facts Dictionary (Recommended Syntax)
Reading facts as top-level variables (ansible_memtotal_mb) still works, but ansible-core now prints a deprecation warning every time you do it. The recommended approach is the ansible_facts dictionary with the fact name stripped of the ansible_ prefix. Save this as facts.yml:
vim facts.yml
One debug task pulls four facts through the dictionary.
---
- name: Facts Demo
hosts: all
tasks:
- name: Use ansible_facts dictionary (recommended)
ansible.builtin.debug:
msg: "OS: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }} | Kernel: {{ ansible_facts['kernel'] }} | RAM: {{ ansible_facts['memtotal_mb'] }}MB"
Run it with ansible-playbook facts.yml and each host reports its own values:
TASK [Use ansible_facts dictionary (recommended)] ******************************
ok: [rocky-managed] => {
"msg": "OS: Rocky 10.2 | Kernel: 6.12.0-211.16.1.el10_2.0.1.x86_64 | RAM: 2709MB"
}
ok: [ubuntu-managed] => {
"msg": "OS: Ubuntu 26.04 | Kernel: 7.0.0-15-generic | RAM: 1962MB"
}
The RAM figures are worth reading too: 2709 MB on a 3 GB VM and 1962 MB on a 2 GB one, because memtotal_mb reports what the kernel can use after its own reservations, not the size you gave the VM. Size checks in a playbook should allow for that gap. Switch to ansible_facts['key'] now rather than when the old form breaks, and you’ll find the exact warning text the legacy syntax produces in the troubleshooting section at the end.
Custom Variables in Playbooks
The vars section at the play level is the simplest way to define custom variables. These are available to all tasks in that play. Create custom_vars.yml:
vim custom_vars.yml
It defines a string, an integer, a list and a dictionary, then prints each one.
---
- name: Test Custom Variables
hosts: all
vars:
app_name: mywebapp
app_port: 8080
app_env: production
allowed_ports:
- 80
- 443
- 8080
db_config:
host: localhost
port: 5432
name: appdb
tasks:
- name: Display simple variables
ansible.builtin.debug:
msg: "App {{ app_name }} runs on port {{ app_port }} in {{ app_env }} mode"
- name: Display list variable
ansible.builtin.debug:
msg: "Allowed ports: {{ allowed_ports | join(', ') }}"
- name: Display dictionary variable
ansible.builtin.debug:
msg: "Database: {{ db_config.name }} on {{ db_config.host }}:{{ db_config.port }}"
All three variable types resolve correctly. We trimmed this to one host because the Ubuntu lines are identical:
TASK [Display simple variables] ************************************************
ok: [rocky-managed] => {
"msg": "App mywebapp runs on port 8080 in production mode"
}
TASK [Display list variable] ***************************************************
ok: [rocky-managed] => {
"msg": "Allowed ports: 80, 443, 8080"
}
TASK [Display dictionary variable] *********************************************
ok: [rocky-managed] => {
"msg": "Database: appdb on localhost:5432"
}
Dictionary values can be accessed using dot notation (db_config.name) or bracket notation (db_config['name']). Bracket notation is safer when the key name contains special characters or clashes with a Python method name, because db_config.items returns the method, not your key. It is also the only form that works when the key itself lives in a variable, as in db_config[setting]. We default to brackets in roles that other people will extend, so a later key named keys or update cannot break a template.
Registered Variables: Capturing Task Output
The register keyword captures the result of a task into a variable. That’s how you make decisions based on command results or carry a value into later tasks. Create register.yml:
vim register.yml
The third task prints the sorted key list of the registered result. We added it because that list is the quickest way to see what you actually have to work with, and on the current core it differs from what older tutorials show. Keep the trick for any module whose return values you have not memorized.
---
- name: Registered Variables
hosts: all
tasks:
- name: Register command output
ansible.builtin.command: uptime
register: uptime_result
changed_when: false
- name: Display registered variable
ansible.builtin.debug:
msg: "Uptime: {{ uptime_result.stdout }}"
- name: List the keys in the registered result
ansible.builtin.debug:
msg: "{{ uptime_result.keys() | sort }}"
Run ansible-playbook register.yml. The stdout key holds the command’s output for each host:
TASK [Display registered variable] *********************************************
ok: [rocky-managed] => {
"msg": "Uptime: 04:37:24 up 16 min, 3 users, load average: 0.25, 0.25, 0.20"
}
ok: [ubuntu-managed] => {
"msg": "Uptime: 04:37:24 up 16 min, 1 user, load average: 0.12, 0.11, 0.13"
}
For a command or shell task, these are the keys you will reach for most:
.stdout: the output as one string.stdout_lines: the same output split into a list.stderr: error output, and where some tools print versions.rc: the return code, 0 on success.changedand.failed: booleans for conditionals
The changed_when: false on the task keeps Ansible from reporting a change for a read-only command, and it also explains the changed_when_result key you’ll see in the next listing. Without it, every run of this playbook would report changed=1 per host even though uptime touches nothing, so your play recap stops telling you anything useful. Put it on every command that only reads state, because a recap full of false changes hides the one task that really did change something.
Where the invocation Key Went (INJECT_INVOCATION)
Older playbooks sometimes read result.invocation.module_args to find out which arguments a module ran with. On the current core that key is not in the task result by default, so the lookup fails with an undefined error. The key listing from the run above shows it plainly, and the second run turns it back on with the environment variable:
ANSIBLE_INJECT_INVOCATION=true ansible-playbook register.yml
Compare the two key lists. The only difference is invocation, sitting between failed and msg in the second one:

Because the setting is var-settable, you can scope it to the one play or host that needs it instead of flipping it globally. ansible-config list shows every way to set it:
ansible-config list -t base | grep -A15 '^INJECT_INVOCATION'
Look at the env, ini and vars entries. The ansible_inject_invocation variable is the one to put in a play’s vars block. Note the version_added line too: the setting and the invocation-off default arrived in the same release, so anyone upgrading from an older core meets both at once.
INJECT_INVOCATION:
default: false
description:
- When enabled, an ``invocation`` key will be added to the task result with the
module/action arguments used. Most callback plugins mask the ``invocation`` key
from task result display by default.
env:
- name: ANSIBLE_INJECT_INVOCATION
ini:
- key: inject_invocation
section: defaults
name: Control task result injection of ``invocation``
type: boolean
vars:
- name: ansible_inject_invocation
version_added: '2.21'
Our advice: don’t turn it on just to keep an old task alive. If a task needs to know an argument, it already has that value as a variable in the play, so read the variable instead of digging it back out of the result.
Once you’ve set things in ansible.cfg, ansible-config dump --only-changed is the fastest way to see what’s actually in effect. It now covers every plugin type by default, so the same host_key_checking = False line shows up twice: once as the base setting and once under the ssh connection plugin. Loading every plugin also prints deprecation notices for the oneline and tree callbacks even when you never use them, which is noise rather than a problem with your config. Add -t base when you only want the old, shorter view:

The ansible-core changelog gives the reason for the new default: every ansible-config action now uses -t all, so a config file with plugin-owned sections such as [ssh_connection] is no longer reported as having unknown sections, and the keys inside those sections are validated. In our dump that shows up as the ssh plugin’s host_key_checking line under CONNECTION.
set_fact: Creating Variables at Runtime
While register captures raw task output, set_fact lets you create new variables from logic. That’s useful for computing values from facts or other variables. Create set_fact.yml:
vim set_fact.yml
The fact is built from an inline conditional on group membership.
---
- name: set_fact Demo
hosts: all
tasks:
- name: Set a fact dynamically
ansible.builtin.set_fact:
server_role: "{{ 'webserver' if inventory_hostname in groups['webservers'] else 'other' }}"
- name: Display dynamic fact
ansible.builtin.debug:
msg: "{{ inventory_hostname }} role is {{ server_role }}"
Both hosts are in the webservers group, so the conditional resolves the same way on each:
TASK [Display dynamic fact] ****************************************************
ok: [rocky-managed] => {
"msg": "rocky-managed role is webserver"
}
ok: [ubuntu-managed] => {
"msg": "ubuntu-managed role is webserver"
}
Facts created with set_fact persist for the rest of the play run on that host. They also sit near the top of the precedence order, above group_vars, host_vars, play vars and even role vars, so a set_fact is the right tool when a runtime decision must beat a static default. Only role params, include params and extra vars outrank it, which the precedence probe further down proves.
group_vars and host_vars: Organizing Variables by Scope
Putting variables directly in playbooks works for small projects. For anything with more than a handful of hosts, group_vars and host_vars directories are the standard approach. Ansible loads them automatically based on inventory group membership and hostname, as long as they sit next to the inventory file or the playbook. That location rule matters more than it looks, because a group_vars directory placed one level too deep is never read and Ansible prints no warning about it. When a group value seems to vanish, check the path before you check the YAML.
group_vars/all: Variables for Every Host
Create the directories, then group_vars/all/main.yml for variables that apply everywhere:
mkdir -p group_vars/{all,rocky,ubuntu} host_vars/{rocky-managed,ubuntu-managed} vars
vim group_vars/all/main.yml
Nothing in it is OS-specific, so it belongs in all rather than in a group file.
---
ntp_server: pool.ntp.org
dns_servers:
- 8.8.8.8
- 8.8.4.4
timezone: UTC
These three values reach every host in the inventory, whatever group it lands in.
Group-Specific Variables
Variables that differ by OS family go in their respective group directories. Open the Rocky group file:
vim group_vars/rocky/main.yml
Rocky uses dnf, firewalld and SELinux.
---
package_manager: dnf
firewall_service: firewalld
selinux_state: enforcing
Then the Ubuntu group file:
vim group_vars/ubuntu/main.yml
Same keys, Ubuntu values.
---
package_manager: apt
firewall_service: ufw
selinux_state: disabled
Keeping the key names identical across groups is what lets one task reference package_manager on both platforms.
host_vars: Per-Host Overrides
When individual hosts need unique values, create a directory matching the inventory hostname. Start with the Rocky host:
vim host_vars/rocky-managed/main.yml
Give it its own port and description.
---
http_port: 8080
server_description: "Rocky Linux application server"
Do the same for the Ubuntu host:
vim host_vars/ubuntu-managed/main.yml
Use a different port so the override is visible in the output.
---
http_port: 9090
server_description: "Ubuntu monitoring server"
Name each directory exactly after the inventory alias (rocky-managed, not the IP). Ansible does not warn about a host_vars directory that matches no host, so a mismatch silently drops every value in it and you only notice when a task picks up the group default.
Testing the Variable Hierarchy
A playbook that pulls from all three levels proves the hierarchy works as expected. Save it as test_hierarchy.yml:
vim test_hierarchy.yml
Each task reads from one level.
---
- name: Test Variable Precedence
hosts: all
tasks:
- name: Show global variables (group_vars/all)
ansible.builtin.debug:
msg: "NTP: {{ ntp_server }} | DNS: {{ dns_servers | join(', ') }} | TZ: {{ timezone }}"
- name: Show group-specific variables
ansible.builtin.debug:
msg: "Package manager: {{ package_manager }} | Firewall: {{ firewall_service }}"
- name: Show host-specific variables
ansible.builtin.debug:
msg: "{{ inventory_hostname }}: {{ server_description }} on port {{ http_port }}"
Run ansible-playbook test_hierarchy.yml and each host gets the right combination of global, group, and host-level values:

The ntp_server value comes from group_vars/all, package_manager from the OS-specific group, and http_port from each host’s own directory. Ansible merges these automatically without any include statements, which is why a new host only needs an inventory line and, at most, a host_vars file. Notice that nothing collided here: each name is defined at exactly one level. Collisions are where people get hurt, and the next two sections deliberately create them so you can see which level wins.
vars_files: Loading Variables from External Files
For application-specific configuration that does not belong in the inventory hierarchy, vars_files loads a YAML file at the play level. Create the file:
vim vars/app_config.yml
Add the application settings.
---
app_name: inventory-service
app_version: "2.5.1"
app_port: 8080
database:
host: db01.internal
port: 5432
name: inventory_db
pool_size: 25
redis:
host: cache01.internal
port: 6379
log_level: info
Reference it from a playbook with the vars_files directive. Save this as test_vars_files.yml:
vim test_vars_files.yml
The path is relative to the playbook’s own directory, not to where you run the command, so keep playbooks in the project root as we do here or the file will not be found.
---
- name: Test vars_files
hosts: all
vars_files:
- vars/app_config.yml
tasks:
- name: Show loaded vars_files variables
ansible.builtin.debug:
msg: "{{ app_name }} v{{ app_version }} on port {{ app_port }}"
- name: Show nested dictionary from vars_files
ansible.builtin.debug:
msg: "DB: {{ database.name }}@{{ database.host }}:{{ database.port }} (pool: {{ database.pool_size }})"
The variables load cleanly from the external file, nested dictionary included:
TASK [Show loaded vars_files variables] ****************************************
ok: [rocky-managed] => {
"msg": "inventory-service v2.5.1 on port 8080"
}
ok: [ubuntu-managed] => {
"msg": "inventory-service v2.5.1 on port 8080"
}
TASK [Show nested dictionary from vars_files] **********************************
ok: [rocky-managed] => {
"msg": "DB: [email protected]:5432 (pool: 25)"
}
ok: [ubuntu-managed] => {
"msg": "DB: [email protected]:5432 (pool: 25)"
}
This pattern works well for separating deployment configuration from playbook logic. Teams often keep one vars/ file per environment (staging, production) and pick the right one at runtime with an extra var in the path, for example vars/{{ env }}.yml. Note where vars_files sits in the order: above play vars but below role vars, so a role’s vars/main.yml still beats a value you loaded here. If that surprises you, the precedence probe below shows it happening.
Extra Variables: The Override Switch
Extra variables passed with -e (or --extra-vars) on the command line have the highest precedence in Ansible. They override everything: play vars, group_vars, host_vars, role vars and set_fact. Create test_extra_vars.yml:
vim test_extra_vars.yml
It sets http_port at play level, which collides with the host_vars values from earlier.
---
- name: Test Extra Variables Override
hosts: all
vars:
http_port: 3000
deploy_env: staging
tasks:
- name: Show http_port value
ansible.builtin.debug:
msg: "HTTP port is {{ http_port }} (deploy env: {{ deploy_env }})"
Without extra vars, the play-level value wins over host_vars (3000 instead of 8080 or 9090):
ansible-playbook test_extra_vars.yml
Both hosts print the play-level default:
TASK [Show http_port value] ****************************************************
ok: [rocky-managed] => {
"msg": "HTTP port is 3000 (deploy env: staging)"
}
ok: [ubuntu-managed] => {
"msg": "HTTP port is 3000 (deploy env: staging)"
}
Now override both values from the command line:
ansible-playbook test_extra_vars.yml -e "http_port=443 deploy_env=production"
Extra vars take priority over everything else:
TASK [Show http_port value] ****************************************************
ok: [rocky-managed] => {
"msg": "HTTP port is 443 (deploy env: production)"
}
ok: [ubuntu-managed] => {
"msg": "HTTP port is 443 (deploy env: production)"
}
This is the mechanism CI/CD pipelines use to inject environment-specific values at deploy time, and it’s also why you should use it sparingly by hand: an extra var silently beats every file in the repo, so a value set with -e in a wrapper script can make a correct host_vars file look broken. You can also pass a YAML or JSON file with -e "@deploy_vars.json". Values given as key=value arrive as strings, so pass a file or JSON when a variable must stay an integer or a boolean.
Variable Filters: Transforming Data
Ansible uses Jinja2 filters to transform variable values inline. They’re applied with the pipe (|) character and can be chained together, and they run on the controller, so a filter costs nothing on the managed host and behaves the same whatever the target OS is. That makes them the right place to normalize data before it reaches a module. All three examples below live in one filters.yml playbook that targets rocky-managed, with server_config: {max_connections: 100} defined in its vars next to the values shown.
String Filters
Common string operations include case conversion, whitespace trimming, and character replacement. They’re useful for normalizing user input or generating config-safe identifiers:
vars:
username: " John Doe "
tasks:
- name: String filters
ansible.builtin.debug:
msg: |
Original: "{{ username }}"
Lower: "{{ username | lower | trim }}"
Upper: "{{ username | upper | trim }}"
Replace: "{{ username | trim | replace(' ', '_') | lower }}"
Filters chain left to right. trim removes whitespace, then replace swaps spaces for underscores:
ok: [rocky-managed] => {
"msg": "Original: \" John Doe \"\nLower: \"john doe\"\nUpper: \"JOHN DOE\"\nReplace: \"john_doe\"\n"
}
The \n sequences are the literal newlines from the msg: | block scalar; debug prints the string JSON-encoded.
List Filters
Lists are a natural fit for packages, ports, and any collection of items. Filters let you count, sort, slice, and join them without writing loops:
vars:
packages:
- nginx
- postgresql
- redis
- certbot
tasks:
- name: List filters
ansible.builtin.debug:
msg: |
Packages: {{ packages | join(', ') }}
Count: {{ packages | length }}
First: {{ packages | first }}
Last: {{ packages | last }}
Sorted: {{ packages | sort | join(', ') }}
Each filter does one job, and the sorted line shows two of them chained.
ok: [rocky-managed] => {
"msg": "Packages: nginx, postgresql, redis, certbot\nCount: 4\nFirst: nginx\nLast: certbot\nSorted: certbot, nginx, postgresql, redis\n"
}
For map, selectattr, combine and the rest of the data-shaping filters, see the Ansible filters guide.
The default Filter
The default filter is one you’ll use constantly. It provides a fallback value when a variable is undefined, which prevents playbook failures:
- name: Default filter (handling undefined variables)
ansible.builtin.debug:
msg: |
Defined: {{ server_config.max_connections | default(50) }}
Undefined: {{ missing_var | default('fallback_value') }}
Boolean: {{ feature_flag | default(false) }}
When a variable exists, its real value is used (100, not the fallback of 50). When it doesn’t, the default kicks in without any error:
ok: [rocky-managed] => {
"msg": "Defined: 100\nUndefined: fallback_value\nBoolean: False\n"
}
For Jinja2 filters inside template files, loops and config generation, see the Ansible Jinja2 templates tutorial in the series.
Special Variables
Ansible provides several built-in “magic” variables that are always available. They give you access to inventory metadata, playbook paths, and the Ansible version itself. Create special_vars.yml:
vim special_vars.yml
Three tasks cover inventory, paths and versions.
---
- name: Special Variables
hosts: all
tasks:
- name: Show inventory-related special variables
ansible.builtin.debug:
msg: "Host: {{ inventory_hostname }} | Groups: {{ group_names | join(', ') }} | All hosts: {{ groups['all'] | join(', ') }}"
- name: Show playbook directory
ansible.builtin.debug:
msg: "Playbook dir: {{ playbook_dir }} | Role path: {{ role_path | default('not in a role') }}"
- name: Show ansible version variable
ansible.builtin.debug:
msg: "Ansible {{ ansible_version.full }} (Python {{ ansible_facts['python_version'] }})"
Each host reports its group membership and the execution context:
TASK [Show inventory-related special variables] ********************************
ok: [rocky-managed] => {
"msg": "Host: rocky-managed | Groups: rocky, webservers | All hosts: rocky-managed, ubuntu-managed"
}
ok: [ubuntu-managed] => {
"msg": "Host: ubuntu-managed | Groups: ubuntu, webservers | All hosts: rocky-managed, ubuntu-managed"
}
TASK [Show playbook directory] *************************************************
ok: [rocky-managed] => {
"msg": "Playbook dir: /home/josphat/ansible-lab | Role path: not in a role"
}
ok: [ubuntu-managed] => {
"msg": "Playbook dir: /home/josphat/ansible-lab | Role path: not in a role"
}
TASK [Show ansible version variable] *******************************************
ok: [rocky-managed] => {
"msg": "Ansible 2.22.0 (Python 3.14.8)"
}
ok: [ubuntu-managed] => {
"msg": "Ansible 2.22.0 (Python 3.14.4)"
}
Two details are easy to misread. playbook_dir is a controller path, so it’s the same on both hosts. ansible_version is also the controller’s version, while python_version is a fact from each managed host, which is why the Python numbers differ. The most commonly used special variables:
| Variable | Description |
|---|---|
inventory_hostname | The name of the host as defined in inventory |
ansible_host | The actual connection address (IP or hostname) |
group_names | List of groups this host belongs to |
groups | Dictionary of all groups and their members |
hostvars | Access variables for any host in inventory |
playbook_dir | Path to the directory containing the playbook |
ansible_version | Dictionary with the controller’s Ansible version info |
role_path | Path to the current role (only inside roles) |
Variable Precedence: The Full Order
When the same variable name is defined in multiple places, Ansible follows a strict precedence order. Knowing it saves hours of asking why a variable is not what you expected. The official precedence list has 22 levels. From lowest to highest:
| Priority | Source | Example |
|---|---|---|
| 1 (lowest) | Command line values (-u, etc.), not variables | ansible-playbook -u deploy |
| 2 | Role defaults (defaults/main.yml) | Intentionally easy to override |
| 3 | Inventory file or script group vars | [web:vars] in inventory |
| 4 | Inventory group_vars/all | Global defaults for all hosts |
| 5 | Playbook group_vars/all | group_vars/ next to the playbook |
| 6 | Inventory group_vars/* | OS or role-specific values |
| 7 | Playbook group_vars/* | Same, beside the playbook |
| 8 | Inventory file or script host vars | web01 http_port=80 in inventory |
| 9 | Inventory host_vars/* | Per-host overrides |
| 10 | Playbook host_vars/* | Same, beside the playbook |
| 11 | Host facts and cached set_facts | Gathered facts |
| 12 | Play vars | vars: section in playbook |
| 13 | Play vars_prompt | Interactive input at runtime |
| 14 | Play vars_files | vars_files: [config.yml] |
| 15 | Role vars (vars/main.yml) | Hard role values |
| 16 | Block vars | Tasks inside that block only |
| 17 | Task vars | That task only |
| 18 | include_vars | Loaded at runtime |
| 19 | set_fact and registered vars | Runtime computed values |
| 20 | Role and include_role params | roles: [{role: x, port: 80}] |
| 21 | Include params | Vars passed to an include |
| 22 (highest) | Extra vars (-e) | -e "http_port=443" |
A table is easy to misremember, so we checked the parts people argue about with a small role. Its defaults/main.yml sets http_port: 80 and app_env: role-defaults, its vars/main.yml sets app_env: role-vars, and the play sets app_env: play-vars before calling set_fact. These are the exact commands we used to create the role’s three files:
mkdir -p roles/demo/defaults roles/demo/vars roles/demo/tasks
printf -- '---\nhttp_port: 80\napp_env: role-defaults\n' > roles/demo/defaults/main.yml
printf -- '---\napp_env: role-vars\n' > roles/demo/vars/main.yml
printf -- '---\n- name: Report from inside the role\n ansible.builtin.debug:\n msg: "role sees http_port={{ http_port }} app_env={{ app_env }}"\n' > roles/demo/tasks/main.yml
The role’s only task prints the same two variables from inside the role. Now create the playbook that calls it:
vim precedence.yml
It sets the play-level value, runs the role, then overrides with set_fact.
---
- name: Precedence Probe
hosts: rocky-managed
gather_facts: false
vars:
app_env: play-vars
roles:
- demo
tasks:
- name: Before set_fact
ansible.builtin.debug:
msg: "http_port={{ http_port }} app_env={{ app_env }}"
- name: Override with set_fact
ansible.builtin.set_fact:
app_env: set-fact
- name: After set_fact
ansible.builtin.debug:
msg: "http_port={{ http_port }} app_env={{ app_env }}"
We ran it twice, once plain and once with -e app_env=extra-vars:

Read the first run top to bottom. The role default of port 80 never shows, because host_vars (8080) outranks role defaults. Role vars beat play vars, so app_env starts as role-vars even though the play set it, which surprises most people the first time. The set_fact then wins over role vars. In the second run the extra var holds from the first task to the last, and the set_fact task reports ok but changes nothing visible. That’s the practical takeaway: use role defaults/ for values you expect users to override, use role vars/ only for values that must never change, and keep -e for deployment-time overrides that should trump everything.
Practical Example: Multi-OS Package Deployment
Pulling the variable types together, here’s a playbook that installs Nginx on both Rocky Linux and Ubuntu, using facts and group_vars to handle the differences automatically. Save it as deploy_nginx.yml:
vim deploy_nginx.yml
It mixes play vars, a registered result, a fact and a group variable.
---
- name: Deploy Nginx with Variables
hosts: webservers
become: true
vars:
nginx_worker_processes: auto
nginx_worker_connections: 1024
server_name: app.example.com
tasks:
- name: Install Nginx
ansible.builtin.package:
name: nginx
state: present
- name: Get Nginx version
ansible.builtin.command: nginx -v
register: nginx_version
changed_when: false
- name: Show installed version
ansible.builtin.debug:
msg: "Installed: {{ nginx_version.stderr }}"
- name: Show OS-specific package manager used
ansible.builtin.debug:
msg: "{{ ansible_facts['distribution'] }} used {{ package_manager }} to install nginx"
The ansible.builtin.package module picks dnf on Rocky and apt on Ubuntu by itself. The package_manager variable comes from the group_vars we set up earlier, and nginx -v writes to stderr, which is why the task reads .stderr instead of .stdout:

Rocky Linux 10.2 installs Nginx 1.26.3 from AppStream, while Ubuntu 26.04 gets 1.28.3. The same playbook handles both without a single OS conditional, and the registered nginx_version could drive version-specific configuration in later tasks. When you do need to branch, the patterns are in the Ansible conditionals and loops tutorial.
Variable Encryption with Ansible Vault
Sensitive variables (database passwords, API keys, certificates) should never sit in plain YAML. Ansible Vault encrypts variable files so they can be committed to version control. For vault IDs, environment separation and CI/CD integration, see the dedicated Ansible Vault tutorial.
The quick version: write the secret to a vars file, then encrypt it with a password file so nothing prompts. These are throwaway lab values; on a real controller, create the password file with an editor so the password never lands in your shell history:
echo 'lab-vault-pass-2284' > ~/.vault_pass && chmod 600 ~/.vault_pass
printf -- '---\ndb_password: "Rk7wq-Lab-2284"\n' > vars/secrets.yml
ansible-vault encrypt vars/secrets.yml --vault-password-file ~/.vault_pass
The file now starts with $ANSIBLE_VAULT;1.1;AES256 followed by hex. Reference it in vars_files like any other file. What changed in the current core is what happens when that value reaches output: Ansible registers every string in a vault-encrypted vars file as a secret and masks it wherever it would be printed. This secret_mask.yml playbook deliberately tries to leak it:
vim secret_mask.yml
It prints the variable, echoes it on the managed host, prints the registered stdout and finally compares the real values.
---
- name: Secret masking with Vault variables
hosts: rocky-managed
vars_files:
- vars/secrets.yml
tasks:
- name: Print the vaulted variable
ansible.builtin.debug:
msg: "Connecting with password {{ db_password }}"
- name: Echo the secret on the managed host
ansible.builtin.command: echo "{{ db_password }}"
register: echo_result
changed_when: false
- name: Show the registered stdout
ansible.builtin.debug:
var: echo_result.stdout
- name: Compare the real value
ansible.builtin.debug:
msg: "Registered value matches the vault value: {{ echo_result.stdout == db_password }}"
Run it with ansible-playbook secret_mask.yml --vault-password-file ~/.vault_pass. Both the debug message and the registered stdout print $REDACTED$, yet the comparison returns True:

That last line is the important one. Masking only changes what gets displayed, so the registered variable still holds the real password and later tasks, conditionals and templates can use it. It also means a debug task is no longer a reliable way to check what a secret resolved to. Compare it inside a task, as above, rather than printing it.
no_log Values in Registered Results
Module options marked no_log (passwords, tokens, keys) follow the same rule. The current core no longer swaps them for the literal placeholder VALUE_SPECIFIED_IN_NO_LOG_PARAMETER inside the registered invocation.module_args. It keeps the real value there, registers it as a secret and masks it only when it is printed. The password option of ansible.builtin.user is one of those options, so we used it on a throwaway appsvc account. Create nolog_invocation.yml:
vim nolog_invocation.yml
It turns on ansible_inject_invocation for this play only, so the registered result carries the arguments the module was called with. The hash is a SHA-512 crypt string made with openssl passwd -6.
---
- name: no_log option values in invocation
hosts: rocky-managed
become: true
vars:
ansible_inject_invocation: true
demo_hash: "$6$labsalt2284$XK3e2wAWC5DgzPJu.WpA8KP2SRUKOX3uDmODxn9OtzKJxuO89F8CCQMu1.rBoFpZr98vTzGTDK5WmcJDe79Ox1"
tasks:
- name: Update the user (password is a no_log module option)
ansible.builtin.user:
name: appsvc
password: "{{ demo_hash }}"
register: user_result
- name: Show the password the module was called with
ansible.builtin.debug:
var: user_result.invocation.module_args.password
- name: Compare it with the real value
ansible.builtin.debug:
msg: "Invocation password matches the hash: {{ user_result.invocation.module_args.password == demo_hash }}"
Run it with ansible-playbook nolog_invocation.yml --limit rocky-managed. The account already existed from an earlier run in our lab, which is why the user task reports ok. That earlier run was a companion playbook, nolog_register.yml, which also registers echo "token-2284" from a task that has no_log: true set on the task itself:
vim nolog_register.yml
The first three tasks create the account and read the module’s own password return key; the last two are the task-level no_log test.
---
- name: no_log values in registered results
hosts: rocky-managed
become: true
vars:
demo_hash: "$6$labsalt2284$XK3e2wAWC5DgzPJu.WpA8KP2SRUKOX3uDmODxn9OtzKJxuO89F8CCQMu1.rBoFpZr98vTzGTDK5WmcJDe79Ox1"
tasks:
- name: Create a user (password is a no_log module option)
ansible.builtin.user:
name: appsvc
password: "{{ demo_hash }}"
register: user_result
- name: Show the password key from the registered result
ansible.builtin.debug:
var: user_result.password
- name: Compare the registered value with the real one
ansible.builtin.debug:
msg: "Registered password matches the hash: {{ user_result.password == demo_hash }}"
- name: Task-level no_log on a command
ansible.builtin.command: echo "token-2284"
register: token_result
no_log: true
changed_when: false
- name: Read the task-level no_log result later
ansible.builtin.debug:
var: token_result.stdout
The screenshot shows the full nolog_invocation.yml run, then only the last two tasks of a nolog_register.yml run:

The first run is the new behaviour: the registered argument prints as $REDACTED$, yet the comparison is True, so the value inside the variable is the real hash. The second run is the trap. A task-level no_log: true hid that task’s own output, but the registered stdout printed in plain text when a later task read it, because token-2284 was never a no_log module option and nothing registered it as a secret. If a value is sensitive, keep no_log on every task that touches it, or load it from Vault so the masking follows it.
One more detail from the same lab: the user module’s own password return key still reads NOT_LOGGING_PASSWORD, and comparing user_result.password with the hash returned False. That string is set by the module, not by the masking, so read the password from your own variable rather than from that key.
Common Mistakes and How to Avoid Them
These three account for most of the variable questions we see, and each one has a quick check.
Error: “‘variable_name’ is undefined”
This means Ansible can’t find the variable at any precedence level. A one-letter typo (htpp_port) reproduces it, and the current core points at the exact column:
[ERROR]: Task failed: Finalization of task args for 'ansible.builtin.debug' failed: Error while resolving value for 'msg': 'htpp_port' is undefined
Task failed.
Origin: /home/josphat/ansible-lab/undefined.yml:7:7
5
6 tasks:
7 - name: Reference a variable that does not exist
^ column 7
<<< caused by >>>
Finalization of task args for 'ansible.builtin.debug' failed.
Origin: /home/josphat/ansible-lab/undefined.yml:8:7
6 tasks:
7 - name: Reference a variable that does not exist
8 ansible.builtin.debug:
^ column 7
<<< caused by >>>
Error while resolving value for 'msg': 'htpp_port' is undefined
Origin: /home/josphat/ansible-lab/undefined.yml:9:14
7 - name: Reference a variable that does not exist
8 ansible.builtin.debug:
9 msg: "Port is {{ htpp_port }}"
^ column 14
fatal: [ubuntu-managed]: FAILED! => {"msg": "Task failed: Finalization of task args for 'ansible.builtin.debug' failed: Error while resolving value for 'msg': 'htpp_port' is undefined"}
Besides typos, the common causes are a host that isn’t in the expected group (so its group_vars never load) and a vars_files path that’s wrong relative to the playbook. To see exactly what Ansible resolves for one host from inventory, group_vars and host_vars, ask the inventory:
ansible-inventory --host ubuntu-managed --yaml
Every inventory-level variable for that host is listed, merged from all three levels.
ansible_host: 10.0.1.12
ansible_user: josphat
dns_servers:
- 8.8.8.8
- 8.8.4.4
firewall_service: ufw
http_port: 9090
ntp_server: pool.ntp.org
package_manager: apt
selinux_state: disabled
server_description: Ubuntu monitoring server
timezone: UTC
If the variable is missing here, the problem is in inventory or group membership, not in the playbook.
INJECT_FACTS_AS_VARS Deprecation Warning
You’ll see this warning when a playbook reads a fact as a top-level variable, here {{ ansible_memtotal_mb }} in a debug task:
[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change. This feature will be removed from ansible-core version 2.24.
Origin: /home/josphat/ansible-lab/facts_legacy.yml:8:14
6 - name: Use injected fact variable (deprecated)
7 ansible.builtin.debug:
8 msg: "RAM: {{ ansible_memtotal_mb }}MB"
^ column 14
Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead.
Nothing fails today, so the warning is easy to ignore until the default flips. The fix is mechanical: ansible_facts['memtotal_mb'] instead of ansible_memtotal_mb. Grep your roles for ansible_[a-z_]* outside the ansible_facts dictionary and convert them in one pass.
Variable Precedence Confusion
When a variable isn’t the value you expect, check each source in order. The most common mistake is defining a value in host_vars and also in play vars, then wondering why the host_vars value is ignored: play vars (level 12) beat inventory host_vars (level 9), exactly as the extra vars test showed with port 3000. The second most common is a role’s vars/main.yml quietly beating the play, as the probe showed. Move such values to defaults/main.yml if they should be overridable, or use -e for one-time overrides.
Quick Reference
Use this table to pick where a new variable belongs before you write it:
| Variable Type | Where Defined | Scope | When to Use |
|---|---|---|---|
| Facts | Gathered from hosts | Per host | OS-specific logic, hardware checks |
| Play vars | vars: in playbook | Per play | Small, self-contained playbooks |
| vars_files | External YAML file | Per play | Environment configs, app settings |
| group_vars | group_vars/ directory | Per group | OS-specific, role-specific defaults |
| host_vars | host_vars/ directory | Per host | Unique per-host overrides |
| Registered | register: keyword | Per host, rest of the run | Capturing command output |
| set_fact | set_fact: module | Per host, rest of the run | Computed values at runtime |
| Extra vars | -e flag | Global | CI/CD overrides, debugging |
| Role defaults | defaults/main.yml | Per role | Values meant to be overridden |
| Role vars | vars/main.yml | Per role | Values that should not change |
| Vault vars | Encrypted vars file | Per play | Secrets, masked in output |
For more Ansible guides, the Ansible automation guide links to every article in the series. The Ansible cheat sheet has quick command references, and the Ansible roles tutorial covers how defaults and role vars fit into a real role layout.