Inventory File Example
Consider the following inventory file, where a DNS server is specified for host “web2”:Tip: If you need to access the DNS server information from another host, magic variables offer a clean solution.
Using the “hostvars” Magic Variable
The magic variablehostvars enables you to retrieve variables set on one host from another host. For example, to retrieve the DNS server defined on “web2”, use the following playbook:
ansible_host parameter, gathering facts permits access to detailed information about other hosts. This includes architecture, devices, mounts, processors, and more. Everything available from a host’s facts can be accessed with hostvars. For instance:
Exploring Other Magic Variables: “groups” and “group_names”
Another essential magic variable isgroups. It returns a list of all hosts within a specified group. In contrast, group_names returns all the groups that the current host belongs to.
Inventory Example with Groups
group_names variable returns the groups that host is a member of (for instance, “web_servers” and “americas”):
Understanding “inventory_hostname”
A related magic variable,inventory_hostname, returns the hostname as specified in the inventory file rather than its fully qualified domain name (FQDN). For example:
Further Reading: For more details on magic variables, consult the official Ansible documentation, especially the sections on variable usage in playbooks.