Chapter #19: How to Use Static and Dynamic Inventories in Ansible
In this chapter, you will understand the key differences between static and dynamic inventories and how to use them in Ansible automation.

In this chapter, we will explain how to use static and dynamic inventory to define groups of hosts in Ansible.
In Ansible, managed hosts or servers that are controlled by the Ansible control node are defined in a host inventory file as explained in. A host inventory file is a text file that consists of hostnames or IP addresses of managed hosts or remote servers.
β Note: By default, Ansible looks for the inventory file in/etc/ansible/hosts
unless another file is specified using the-i
option.
Managed hosts can either be listed as individual entries or categorized under a group name, as we shall later see. In Ansible, there are two types of inventory files: Static and Dynamic.
Letβs have a look at each one of these and see how we can manage them. By now, we assume that you have already installed Ansible on your Control Node and configured a Passwordless SSH connection to your managed hosts.
Static Host Inventory File
In Ansible, a static inventory file is a plain text file that contains a list of managed hosts declared under a host group using either hostnames or IP addresses.
A host group name is enclosed in square brackets, i.e [group name]
. The managed host entries are later listed below the group name, each on its own line.
As discussed earlier, the hosts are listed using either hostnames or IP addresses.
[group name]
Host A ip_address
Host B ip_address
Host C ip_address
For purposes of illustration, we shall create a static inventory file.
mkdir test_lab && cd test_lab
vim hosts
Static Inventory File.
[webservers]
173.82.115.165
[database_servers]
173.82.220.239
[datacenter:children]
webservers
database_servers
Save the file and exit.
As you can see in the inventory file above, we have created 2 host groups: webservers
and database_servers
. Also, we have created an additional group called datacenter
that includes a group of host groups denoted by :children
suffix as seen above.
Ansible also allows groups of hosts to be placed under a group name. In the inventory file above, the webservers
and database_servers
groups have been placed under the datacenter
.
β Tip: Inventory files can also be written in YAML format, though INI-style is more common for simple static inventories.
Example YAML static inventory:
all:
children:
webservers:
hosts:
web1:
web2:
database_servers:
hosts:
db1:
db2:
Using Host Variables in Static Inventory
You can define variables for individual hosts or for groups.
Inline host variables:
[webservers]
web1 ansible_user=admin ansible_port=2222 ansible_ssh_private_key_file=~/.ssh/id_rsa
Group-level variables:
[webservers:vars]
ansible_user=admin
ansible_port=2222
These are useful when your managed nodes require different users, ports, or authentication methods.