{{ hostvars["web2"].dns_server }} variable set for “web2” is not available on “web1” or “web3.”
This is where magic variables become essential, allowing a subprocess running on one host to access variables from another host.
Accessing Variables from Other Hosts
The magic variablehostvars lets you retrieve variables from any host defined in your inventory. For instance, to obtain the DNS server IP address specified on “web2” from any host, you can use the following playbook:
Note: When facts are gathered, you can access additional details about other hosts (such as their IP address, architecture, devices, mounts, or processor details) using a similar approach.The playbook below demonstrates how to access several facts from “web2”:
Using Groups and Group Names
Another valuable magic variable isgroups, which provides a list of hosts under a specified inventory group. Consider the following inventory configuration:
group_names returns all the groups that the current host is a member of. For example, if you run a task on “web1” that prints group_names, it will output both “web_servers” and “americas”:
Other Common Magic Variables
Below are some other frequently used magic variables in Ansible:-
inventory_hostname:
This variable holds the name of the host as specified in the inventory file, which might differ from its fully qualified domain name (FQDN). For example: -
Nested Fact Access:
You can retrieve deeply nested facts by combining dictionary accesses. For example: -
Other Play-Related Variables:
ansible_play_hostslists all hosts still active in the current play.ansible_play_batchcontains the hostnames in the current batch of execution.ansible_playbook_pythonspecifies the path to the Python executable used by the Ansible command-line tool.
Note: For more detailed information on magic variables and their usage, please refer to the official Ansible documentation.This concludes our discussion on magic variables in Ansible. By leveraging these powerful features, you can create more dynamic and efficient playbooks that adapt based on the data available across your entire inventory.