One of the most fundamental features of Ansible is its ability to manage multiple machines simultaneously. To do this, Ansible works with an inventory of hosts which is essentially a list of nodes that Ansible will manage.
In the Ansible inventory, each machine or host has a name that is governed by the inventory_hostname variable. This variable refers to the name of the current node that Ansible is currently working on.
In this tutorial, we will learn how we can use the inventory_hostname parameter which can allow you to perform the node-specific operations.
What Is Ansible Inventory_Hostname?
When we run a playbook on a list of hosts, Ansible iterates over each host in the list. For each host, the inventory_hostname variable is set to the name of the currently running host.
For example, we have an inventory file as follows:
web1.linuxhint.com
web2.linuxhint.com
When Ansible is running a task or a playbook that targets the webservers group, the inventory_hostname is set to “web1.linuxhint.com” during the iteration that processes that host and “web2.linuxhint.com” for the next host.
How to Use the Inventory_Hostname Variable
Let us cover some practical examples of using the inventory_hostname in an Ansible playbook.
Start by creating an inventory file with the following entries:
web1.linuxhint.com
web2.linuxhint.com
Next, we write a playbook that uses the inventory_hostname variable as shown in the following example:
- name: Display the inventory_hostname
hosts: webservers
tasks:
- name: Print the inventory_hostname
debug:
msg: "The current host is: {{ inventory_hostname }}"
Output:
ok: [172.18.0.9] => {
"msg": "The current host is: web1.linuxhint.com"
}
ok: [172.18.0.9] => {
"msg": "The current host is: web2.linuxhint.com"
}
Conclusion
The inventory_hostname variable is a fundamental and powerful feature in Ansible that allows us to get the name of the current node that is being managed. We hope you enjoyed this post.