Ansible is a powerful, free, and open-source tool commonly that is used in automation tasks such as configuration management, application deployment, infrastructure management, etc.
One of the powerful features it offers is variables which can be used to customize how Ansible interacts with target machines.
In Ansible, the hostvars variable refers to a dictionary that contains information about all the hosts. This dictionary allows us to access the variables that are associated with other hosts even when working on a playbook that is dedicated to a single host.
In this tutorial, we will learn how to use the hostvars variable. We will learn its role, how it can benefit us, and how to use it in a playbook.
When to Use Hostvars
The main question you may ask before learning about the hostvars variable is, “when would I need to use it?”
Consider a multi-server environment where specific tasks on one server may depend on another server’s data or state. Using the hostvars variable, we can access the variables set for any host in the inventory which allows us to quickly and efficiently integrate the inter-host dependencies.
How to Use Hostvars
Let us now proceed and discuss how we can use the hostvars in Ansible.
Consider a scenario where you have two servers: a database server and an application server.
In this scenario, the application server needs the IP address of the database server so it can communicate with the database server.
Assume that we have the inventory file defined as follows:
In a playbook, if we want to use the IP of dbserver when setting up the appserver, we can use the hostvars variable as follows:
Let’s consider we have multiple app servers and we want to print the IPs of all servers in our database server for some logging purposes.
To do this, we can use a loop in the playbook as shown in the following example:
We can also combine the hostvars dictionary with ansible conditions to perform an action when the condition is met as demonstrated in the following example:
If the variables are nested, we can drill down the dictionary as demonstrated in the following playbook example:
We learned how to use the hostvars in Ansible. This tool is powerful in Ansible’s arsenal, especially in complex multi-server environments where the tasks and roles might have interdependencies.