How to Use Static and Dynamic Inventories in Ansible – Part 4

In this Part 4 of Ansible Series, we will explain how to use static and dynamic inventory to define groups of hosts in Ansible.

In an Ansible, managed hosts or servers which 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.

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 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.

NOTE: It’s not mandatory to place managed hosts in a host group. You can simply list them using their hostnames or IP addresses for example.

173.82.202.239
172.82.115.165
load_balancer.pnl.com

Let’s now use a few Ansible commands for referencing the host inventory file. The basic syntax for inventory management is as shown.

$ ansible {host-pattern} -i /path/of/inventory/file --list-hosts

For example,

$ ansible all -i /root/test_labs/hosts --list-hosts
List Ansible Hosts
List Ansible Hosts

Alternatively, you can use the wildcard character * to replace ‘all’ argument.

$ ansible * -i /root/test_labs/hosts --list-hosts
List Ansible Hosts Using Wildcards
List Ansible Hosts Using Wildcards

To list hosts in a group, specify the host group in the place of host-pattern.

$ ansible webservers -i /root/test_labs/hosts --list-hosts
List Ansible Hosts in Group
List Ansible Hosts in Group

Dynamic Host Inventory File

In a configuration – especially a cloud setup such as AWS where the inventory file keeps constantly changing as you add or decommission servers, keeping tabs on the hosts defined in the inventory file becomes a real challenge. It becomes inconvenient going back to the host file and updating the list of hosts with their IP addresses.

And this is where a dynamic inventory comes to play. So what is a dynamic inventory? A dynamic inventory is a script written in Python, PHP or any other programming language. It comes in handy in cloud environments such as AWS where IP addresses change once a virtual server is stopped and started again.

Ansible already has developed inventory scripts for public cloud platforms such as Google Compute Engine, Amazon EC2 instance, OpenStack, RackSpace, cobbler, among others.

What are the advantages of a dynamic inventory over a static inventory?
  • Dynamic inventories do a perfect job of reducing human error as information is gathered using scripts.
  • Minimal effort is required in managing inventories.

You can write your own customize dynamic inventory in a programming language of your choice. The inventory should return a format in JSON when appropriate options are passed.

Utilize an Existing Dynamic Inventory Script

A script that is used to create a dynamic inventory has to be made executable so that Ansible can use it.

To retrieve information about the hosts inside a dynamic inventory script simply run.

# ./script --list 

As pointed earlier, the output should be in JSON in the format below.

A dictionary comprising of groups (i.e webservers, database_Servers)
  • A list of managed hosts per group
  • A dictionary of variables
Meta dictionary
  • Hosts and hostvars
Sample Output
{
  "webservers": {
    "hosts": [
      "webserver1.example.com",
      "webserver2.example.com"
    ],
    "vars": {}
  },
  "database_servers": {
    "hosts": [
      "mysql_db1",
      "mysql_db2"
    ],
    "vars": {}
  },
  "_meta": {
    "hostvars": {
      "mysql_db2": {},
      "webserver2.example.com": {},
      "webserver1.example.com": {}, 
      "mysql_db1": {}
    }
  }
}
Conclusion

In this article, we have demonstrated how to create both static and dynamic inventories. In summary, a static inventory file is a plain text file containing a list of managed hosts or remote nodes whose numbers and IP addresses remain fairly constant.

On the other hand, a dynamic host file keeps changing as you add new hosts or decommission old ones. The IP addresses of hosts are also dynamic as you stop and start new host systems. We do hope that you found this tutorial informative.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

James Kiarie
This is James, a certified Linux administrator and a tech enthusiast who loves keeping in touch with emerging trends in the tech world. When I'm not running commands on the terminal, I'm taking listening to some cool music. taking a casual stroll or watching a nice movie.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

8 Comments

Leave a Reply
  1. I love tecmint and this is another worthwhile link with an explanation of network inventory for ansible using JSON (i.e. an ex python step).

    Please change “hostvars” to “vars” as my version of ansible issues a warning.

    [derek@socorro JinaTemplates]$ ansible -i network.json –list-hosts all
    [WARNING]: Skipping unexpected key (hostvars) in group (_meta), only “vars”, “children” and “hosts” are valid
    hosts (8):
    eng-pe2
    eng-pe1
    spn-2

    Reply
  2. Hi,

    Good Ansible articles!

    May I suggest a syntax correction?

    In the “Dynamic Host Inventory File” section, in the fourth line, change :

    A dynamic inventory is a shell script written in Python, PHP or any other programming language.

    by

    A dynamic inventory is a script written in Python, PHP or any other programming language.

    Thanks

    Reply
  3. Hi James,

    After a dynamic inventory script successfully (using ./somescript –list) how do you use the JSON response as your hosts to execute a playbook?

    Reply
  4. Yes, but I want to know the content of your Dynamic Inventory Script file, I searched a lot and I’m just a low-level person. I want JSON results like you, please let me know.
    I would be happy to be able to get your contact

    Reply
    • Yes, but I want to know the content of your Dynamic Inventory Script file, I searched a lot and I’m just a low-level person. I want JSON results like you, please let me know.

      I would be happy to be able to get your contact

      Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.