Getting Started: Understanding Ansible Inventory File for Network Automation


Ansible is a powerful tool that can be used to automate network tasks. One of the first things you need to do is create an inventory file. This file tells Ansible which hosts/switches or routers to manage and how to connect to them.

There are a few different ways to create an inventory file. The simplest way is to use the built-in inventory file, which is located at /etc/ansible/hosts. This file contains a list of all the hosts that Ansible knows about.

If you want to create your own inventory file, you can do so in a variety of formats.
The most common format is YAML. To create a YAML inventory file, open a text editor and create a file called inventory.yml. In this file, you will need to list all the hosts that you want Ansible to manage. Each host should be on its own line. You can also specify the type of host, the IP address, and the SSH port.

Here is an example of a YAML inventory file:

Code snippet

---
hosts:
  - name: localhost
    type: router
    ip: 127.0.0.1
    port: 22
  - name: remote-router
    type: router
    ip: 192.168.1.1
    port: 22

Once you have created your inventory file, you can use it to run Ansible commands. For example, to run a command on all the hosts in your inventory, you would use the following command:

Code snippet

ansible -i inventory.yml -m ping all

This command will send a ping request to all the hosts in your inventory.

You can also add comments to your inventory file by starting the line with a # character. For example, the following inventory file contains a comment:

---
hosts:
# Cisco Router at South Building
  - name: remote-router  
    type: router
    ip: 10.5.5.5
    port: 22

Ansible will ignore any lines that start with a # character, which is handy for adding comments to the code for later reference.

Ansible also supports a variety of other inventory formats, including CSV, JSON, and EC2. For more information, please see the Ansible documentation.

Here are some additional tips for creating an inventory file:

  • Use descriptive names for your hosts. This will make it easier to understand your inventory file.
  • Use the same IP address for each host in your inventory. This will make it easier for Ansible to connect to the hosts.
  • Use a consistent format for your inventory file. This will make it easier to manage your inventory file.

I hope this helps!

David Prestidge

IT Industry Professional for over 20 years, with experiance from Helpdesk, Systems Administration and Network Administration. I now run Bonded Stream, a MSP that focuses on Network Management at scale.

Recent Posts