How to Use Variables in an Ansible Inventory File with Examples?

Using Variables in Ansible Inventory File: An Illustrative Guide

Ansible, a robust IT automation tool, allows you to manage your infrastructure more efficiently. In this tutorial, we will learn how to use variables in an Ansible Inventory file, an essential feature for simplifying and customizing your Ansible playbooks.

Understanding Ansible Inventory Variables

Inventory variables in Ansible allow you to define values that can be used in your playbooks. You can assign variables to individual hosts, groups of hosts, or even all hosts. This allows you to customize the behavior of your playbooks based on the particular hosts they’re running against.

Assigning Variables to a Host

To assign a variable to a host, add the variable and its value after the hostname in the inventory file, separated by a space. Here’s a basic example:

In this case, the variable http_port with the value 80 is assigned to webserver1.example.com.

Assigning Variables to a Group

To assign a variable to a group of hosts, create a new section using the group’s name followed by :vars, then list the variables underneath. For example:

In this example, all hosts in the webservers group have the http_port variable set to 80.

Advanced Variable Usage: Hierarchical Group Variables

You can also define variables hierarchically, allowing you to set default variables for all hosts while overriding them for specific groups or hosts.

In this setup, http_port is set to 80 for the web servers and 3306 for the database servers. The environment variable is set to development for all hosts.

Utilizing Variables in the Playbook

Given the above inventory file, here’s how we can utilize these variables within an Ansible playbook:

This playbook performs the following tasks:

  • For all hosts, it displays a message stating the environment type.
  • For the web servers, it installs Nginix, ensures the service is running and enabled, and opens the HTTP port in the firewall.
  • For the database servers, it installs MySQL, ensures the service is running and enabled, and opens the DB port in the firewall.

Variables from the inventory file, environment and http_port, are used in this playbook. Ansible substitutes the variable with the value defined in the inventory file.

Conclusion

Using variables in Ansible inventory files is a powerful way to customize your playbooks’ behavior. By defining and overriding variables at the host and group levels, you can create flexible playbooks that adapt to the needs of your infrastructure. Whether you’re managing a few machines or a large-scale deployment, understanding inventory variables will enhance your Ansible usage significantly.