Learning DevOps
上QQ阅读APP看书,第一时间看更新

The inventory file

For Ansible to configure hosts when running the playbook, it needs to have a file that contains the list of hosts, that is, the list of IP or Fully Qualified Domain Name (FQDN) addresses of the target machines. This list of hosts is noted in a static file called the inventory file.

By default, Ansible contains an inventory file created during its installation; this file is /etc/ansible/hosts, and it contains several inventory configuration examples. In our case, we will manually create and fill this file in a directory of our choice, such as devopsansible.

Let's do this step by step:

  1. The first step is the creation of the directory with the following basic command:
mkdir devopsansible
cd devopsansible
  1. Then, let's create a file named myinventory (without an extension), in which we write the IP addresses or the FQDN of the targets hosts, as in this example:
192.10.14.10
mywebserver.entreprise.com
localhost

When Ansible is executed based on this inventory, it will execute all of the requested actions (playbook) on all hosts mentioned in this inventory.

For more information about the inventory file, read the documentation:  https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html.

However, in the real usage of Ansible in enterprise, the same Ansible code (or playbook) contains the configuration actions performed for all of the VMs of an application. Since these VMs have different roles within the application, such as an application that consists of one (or more) web server and one database server, we must divide our inventory to properly separate the VMs by functional roles.

To group VMs by role, in the inventory, we will organize our VMs into groups that will be noted between [], which gives us the following inventory:

[webserver]
192.10.20.31
mywebserver.exemple.com

[database]
192.20.34.20

In this example, we have defined two groups, webserver and database, and all hosts are distributed in each of their groups.

For another example, we can also group the hosts by environments with this sample inventory:

[dev]
192.10.20.31
192.10.20.32

[qa]
192.20.34.20
192.20.34.21

[prod]
192.10.12.10
192.10.12.11
We will see later in this chapter how these groups will be used in playbook writing.

Now, let's look at how to complete our inventory with the configuration of hosts.