We know a little about inventory file as of now, like, it has the list of hostnames that a controller node could communicate with. But, there is a lot a inventory file can do and we in this post will touch a bit on some of the features.
By default, Ansible uses /etc/ansible/hosts file as the inventory file, but it is also possible to specify the inventory file during the runtime with the full path. Ansible also adds an entry for local host automatically and this does not mean that ansible can run without any entries in the inventory file. To add the local host explicitly, use localhost ansible_connection=local, this way ansible communicates with local host directly instead of using SSH.
Simple inventory file
Groups – hostnames can be grouped as below and hosts can be part of as many groups as possible and it does not impact the functionality of the ansible
Group of Groups – Groups can also be grouped with a keyword :children, without children keyword it would be considered as another group and does not solve the purpose.
These are used when we would need to specify some parameters explicitly for some hosts, say we want to change the user we want to ssh with or add python interpreter for hosts running Python 3. Below is the usage.
Some more Behavioral Parameters
What if, you want to specify behavioral parameters for many number of hosts, we can leverage on groups and variables and the keyword used for this is :vars. Here, all the servers in db group will ssh using the user test and his password.
Variable Scope and Precedence
host_vars/group_vars – Although specifying group variables in the inventory file is a good practice, it is not the best when there are large number of hosts and the infrastructure is growing fast; especially in the days of cloud dominated operations. Now comes the variable files i.e files that exclusively store variables. These variable files are to be written in YAML and placed under directories host_vars and group_vars depending on the scope of the variables.
What if a variable setting configured at both group_var and host_var? Well, the host_var settings has the precedence over all the settings. Ansible first looks for settings configured in ‘all’ then ‘group_vars’ directory and then ‘host_vars’ directory. Lets consider an example, here is the tree output.
As you have seen earlier, Groups_inventory has hosts grouped. When coming to applying variables, if there are any mentioned in ‘all’ file, they are applied to all hosts in all groups. If there are variables mentioned in ‘file’, they are only applied to file group. Any variables mentioned by the host name in host_vars has the highest precedence and this wins.
Hope this was informative. Thanks!