Quiz Entry - updated: 2026.11.05
What are magic variables, and what do hostvars, group_names, groups and inventory_hostname contain?
hostvars: the variables of every managed host, so one host can read another's.group_names: the groups the current host belongs to.groups: every group in the inventory and its hosts.inventory_hostname: the current host's name as written in the inventory.
Magic variables are set by Ansible itself. Their names are reserved: don't define your own variables with these names.
Two details worth knowing:
hostvarscontains a host's facts only once facts have been gathered for that host, in this play or an earlier play of the run. Before that,hostvars['db1']['ansible_facts']is empty.inventory_hostnamecan differ fromansible_facts['hostname']. The inventory might call a hostweb1(or an IP address, or an alias withansible_host) while the machine calls itselfsrv-4711. Useinventory_hostnamewhen you mean "this inventory entry", and the fact when you mean what the OS reports.
Go deeper:
Special variables (official docs) — the full list of magic variables.
Information about Ansible: magic variables (official docs) — examples with
hostvarsandgroups.