Ansible stores the information for the nodes that it manages using Ansible variables. Ansible variables can be declared in multiple locations. However, in observing the best practices for Ansible, we will outline the two main parts where Ansible looks for variables for the nodes that are declared in the inventory file.
Using Ansible's variables
Getting ready
In order to follow along with this recipe, an Ansible inventory file must be already defined as outlined in the previous recipes.
How to do it...
In the inventory file, we define hosts and we group the hosts into groups. We now define two directories that Ansible searches for group variables and host variables:
- Create two folders, group_vars and host_vars:
$ cd ch1_ansible
$ mkdir group_vars host_vars
- Create ios.yml and junos.yml files inside group_vars:
$ touch group_vars/cisco.yml group_vars/juniper.yml
- Create mx1.yml and csr1.yml inside host_vars:
$ touch host_vars/csr1.yml host_vars/mx1.yml
- Populate variables in all the files, as shown here:
$echo 'hostname: core-mx1' >> host_vars/mx1.yml
$echo 'hostname: core-mx2' >> host_vars/mx2.yml
$echo 'hostname: edge-csr1' >> host_vars/csr1.yml
$echo 'hostname: edge-csr2' >> host_vars/csr2.yml
$echo 'os: ios' >> group_vars/cisco.yml
$echo 'os: junos' >> group_vars/juniper.yml
How it works...
We created the following structure of directories and files to host our variables, as shown in the following diagram:
All files inside the group_vars directory contain the group variables for the groups that we have defined in our inventory and they apply to all the hosts within this group. As for the files within host_vars, they contain variables for each host. Using this structure, we can group variables from multiple hosts into a specific group file and variables that are host-specific will be placed in a separate file specific to this host.
There's more...
In addition to host_vars and group_vars, Ansible supports the definition of variables using other techniques, including the following:
- Using the vars keyword within the play to specify multiple variables
- Using vars_files to define variables in a file and having Ansible read these variables from this file while running the playbook
- Specifying variables at the command line using the --e option
In addition to the user-defined variables that we can specify, Ansible has some default variables that it builds dynamically for its inventory. The following table captures some of the most frequently used variables:
inventory_hostname | The name of the hosts as defined in the inventory (for example, csr1 and mx1) |
play_hosts | A list of all the hosts included in the play |
group_names | A list of all the groups that a specific host is a part of (for example, for csr1 this will be [edge, Cisco, network]) |