Ansible Magic Variables: Complete Reference Guide (2026)
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
Complete guide to Ansible magic variables (special variables). hostvars, groups, inventory_hostname, play_hosts, ansible_facts, role_path.
Ansible Magic Variables: Complete Reference Guide (2026)
Magic variables (special variables) are automatically set by Ansible and available in every playbook. They provide information about hosts, groups, the current play, and the execution environment. This guide covers every important magic variable with practical examples.
See also: ansible.builtin.set_fact Module: Set Variables Dynamically (Complete Guide)
Host and Inventory Variables
inventory_hostname
The name of the current host as defined in inventory:
- name: Print current host
ansible.builtin.debug:
msg: "Running on {{ inventory_hostname }}"
inventory_hostname_short
The short hostname (first part before the dot):
- ansible.builtin.debug:
msg: "Short name: {{ inventory_hostname_short }}"
# web01.example.com → web01
ansible_host
The actual IP/hostname used to connect (may differ from inventory_hostname):
# inventory.ini
[webservers]
web01 ansible_host=192.168.1.10
# playbook
- ansible.builtin.debug:
msg: "Inventory name: {{ inventory_hostname }}, connects to: {{ ansible_host }}"
ansible_play_hosts / play_hosts
List of all hosts in the current play that haven't failed:
- name: Show all hosts in this play
ansible.builtin.debug:
msg: "Active hosts: {{ ansible_play_hosts }}"
run_once: true
- name: Configure primary/secondary based on host list
ansible.builtin.template:
src: cluster.conf.j2
dest: /etc/app/cluster.conf
vars:
primary: "{{ ansible_play_hosts[0] }}"
secondary: "{{ ansible_play_hosts[1:] }}"
ansible_play_batch
Hosts in the current batch (affected by serial):
- hosts: webservers
serial: 2
tasks:
- ansible.builtin.debug:
msg: "This batch: {{ ansible_play_batch }}"
Group Variables
groups
Dictionary of all groups and their hosts:
- name: List all webservers
ansible.builtin.debug:
msg: "Webservers: {{ groups['webservers'] }}"
- name: List all groups
ansible.builtin.debug:
msg: "Groups: {{ groups.keys() | list }}"
- name: Configure load balancer with all web backends
ansible.builtin.template:
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
vars:
backends: "{{ groups['webservers'] }}"
group_names
List of groups the current host belongs to:
- name: Show host's groups
ansible.builtin.debug:
msg: "{{ inventory_hostname }} belongs to: {{ group_names }}"
- name: Apply config only to hosts in 'production'
ansible.builtin.template:
src: app.conf.j2
dest: /etc/app/app.conf
when: "'production' in group_names"
See also: Ansible Environment Variables: Set, Read & Manage env vars (Complete Guide)
Cross-Host Data Access
hostvars
Access any host's variables from any other host:
- name: Get database server IP for app config
ansible.builtin.template:
src: app.conf.j2
dest: /etc/app/app.conf
vars:
db_ip: "{{ hostvars['db01']['ansible_default_ipv4']['address'] }}"
- name: Print all hosts' IPs
ansible.builtin.debug:
msg: "{{ item }}: {{ hostvars[item]['ansible_host'] | default('unknown') }}"
loop: "{{ groups['all'] }}"
Playbook and Play Variables
ansible_playbook_python
Path to the Python interpreter on the controller:
- ansible.builtin.debug:
var: ansible_playbook_python
# /usr/bin/python3
ansible_version
Ansible version information:
- ansible.builtin.debug:
msg: "Ansible {{ ansible_version.full }} ({{ ansible_version.major }}.{{ ansible_version.minor }})"
playbook_dir
Directory of the current playbook:
- ansible.builtin.debug:
msg: "Playbook is at: {{ playbook_dir }}"
- name: Include file relative to playbook
ansible.builtin.include_vars:
file: "{{ playbook_dir }}/vars/{{ env }}.yml"
role_path
Path of the currently executing role:
# Inside a role's tasks/main.yml:
- name: Copy role-specific file
ansible.builtin.copy:
src: "{{ role_path }}/files/config.ini"
dest: /etc/app/config.ini
ansible_check_mode
Whether running in check (dry-run) mode:
- name: Skip destructive tasks in check mode
ansible.builtin.shell: /opt/scripts/deploy.sh
when: not ansible_check_mode
ansible_diff_mode
Whether running with --diff:
- name: Extra output in diff mode
ansible.builtin.debug:
msg: "Running in diff mode — showing changes"
when: ansible_diff_mode
See also: Ansible extra vars (-e): Pass Variables from Command Line (Complete Guide)
Loop Variables
ansible_loop
Extended loop information (requires extended: true):
- name: Process with loop info
ansible.builtin.debug:
msg: "{{ ansible_loop.index }}/{{ ansible_loop.length }}: {{ item }}"
loop: [a, b, c]
loop_control:
extended: true
Available attributes:
• ansible_loop.index — 1-based position
• ansible_loop.index0 — 0-based position
• ansible_loop.first — true on first iteration
• ansible_loop.last — true on last iteration
• ansible_loop.length — total items
• ansible_loop.previtem — previous item
• ansible_loop.nextitem — next item
Task and Role Variables
ansible_role_name / role_name
Name of the current role:
- ansible.builtin.debug:
msg: "Executing role: {{ ansible_role_name | default('none') }}"
ansible_parent_role_names
List of parent roles (for nested role calls):
- ansible.builtin.debug:
msg: "Called by: {{ ansible_parent_role_names | default([]) }}"
ansible_run_tags / ansible_skip_tags
Tags applied to the current run:
- name: Show active tags
ansible.builtin.debug:
msg: "Run tags: {{ ansible_run_tags }}, Skip tags: {{ ansible_skip_tags }}"
Connection Variables
ansible_connection
Connection type used:
- ansible.builtin.debug:
msg: "Connection: {{ ansible_connection }}"
# ssh, local, winrm, etc.
ansible_user
The remote user for the connection:
- ansible.builtin.debug:
msg: "Connected as: {{ ansible_user | default('not set') }}"
Quick Reference Table
| Variable | Returns | Example Value |
|----------|---------|---------------|
| inventory_hostname | Host name from inventory | web01.example.com |
| inventory_hostname_short | Short hostname | web01 |
| ansible_host | Connection address | 192.168.1.10 |
| groups | All groups → hosts dict | {'webservers': ['web01']} |
| group_names | Current host's groups | ['webservers', 'production'] |
| hostvars | All hosts' variables | Dict of dicts |
| ansible_play_hosts | Active hosts in play | ['web01', 'web02'] |
| play_hosts | Same as ansible_play_hosts | ['web01', 'web02'] |
| playbook_dir | Playbook directory | /home/user/ansible |
| role_path | Current role path | /home/user/roles/nginx |
| ansible_version | Ansible version dict | {'full': '2.17.0'} |
| ansible_check_mode | Check mode active | true / false |
| ansible_diff_mode | Diff mode active | true / false |
FAQ
What are Ansible magic variables?
Magic variables (special variables) are automatically set by Ansible during playbook execution. They provide information about hosts, groups, the play, and the environment without you defining them. Examples include inventory_hostname, groups, hostvars, and ansible_play_hosts.
How do I access another host's variables in Ansible?
Use hostvars: hostvars['other_host']['variable_name']. The target host must be in the inventory, and its facts must be gathered (or the variable must be set in inventory/group_vars).
What is the difference between inventory_hostname and ansible_hostname?
inventory_hostname is the name as defined in your inventory file. ansible_hostname is the actual system hostname gathered from the remote machine via facts. They may differ if your inventory uses aliases or FQDNs.
How do I list all hosts in a group from a playbook?
Use groups['group_name'] to get a list of all hosts in that group. For example: groups['webservers'] returns ['web01', 'web02'].
How do I check if a host is in a specific group?
Use when: "'group_name' in group_names" in your task. The group_names magic variable contains a list of all groups the current host belongs to.
Conclusion
Ansible magic variables give you access to inventory, host, group, and play information without explicit variable definitions. Master hostvars, groups, group_names, and inventory_hostname for dynamic playbooks that adapt to your infrastructure.
Related Articles
• Ansible Variables: Complete Guide • Ansible Facts: Gather System Information • Ansible Inventory: Complete Guide • Ansible debug Module: Print Variables & MessagesCategory: troubleshooting