How to set default inventory file path in Ansible

AnsibleAnsibleBeginner
Practice Now

Introduction

Ansible is a widely-used IT automation tool that simplifies the management of infrastructure and applications. In this tutorial, we will explore how to set the default inventory file path in Ansible, ensuring efficient and consistent infrastructure management. An inventory file in Ansible contains a list of hosts that Ansible manages. By configuring a custom inventory file location, you can better organize your automation workflow.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ansible(("Ansible")) -.-> ansible/ModuleOperationsGroup(["Module Operations"]) ansible(("Ansible")) -.-> ansible/InventoryManagementGroup(["Inventory Management"]) ansible/ModuleOperationsGroup -.-> ansible/command("Execute Commands") ansible/ModuleOperationsGroup -.-> ansible/ping("Network Test") ansible/InventoryManagementGroup -.-> ansible/groups_inventory("Define Inventory Groups") ansible/InventoryManagementGroup -.-> ansible/host_variables("Set Host Variables") subgraph Lab Skills ansible/command -.-> lab-415865{{"How to set default inventory file path in Ansible"}} ansible/ping -.-> lab-415865{{"How to set default inventory file path in Ansible"}} ansible/groups_inventory -.-> lab-415865{{"How to set default inventory file path in Ansible"}} ansible/host_variables -.-> lab-415865{{"How to set default inventory file path in Ansible"}} end

Understanding Ansible Inventory

Before we configure a custom inventory file path, let's understand what an Ansible inventory is and how it works by default.

What is an Ansible Inventory?

An Ansible inventory is a file that contains information about the hosts that Ansible will manage. By default, Ansible looks for the inventory file at /etc/ansible/hosts. The inventory can be in various formats, but the most common is an INI-style file or a YAML file.

Let's check if Ansible is installed correctly on our system:

ansible --version

You should see output similar to this:

ansible [core 2.12.x]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/labex/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.10.x (default, Ubuntu, etc.)

Now, let's look at the default inventory file location:

cat /etc/ansible/hosts

This file might be empty or contain example host configurations. The default inventory file often looks like this:

## Example inventory file

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com

In this format:

  • [webservers] and [dbservers] are group names
  • The hostnames or IP addresses listed under each group belong to that group

For our lab, we'll create our own custom inventory file in a different location.

Creating a Custom Inventory File

Now that we understand what an inventory file is, let's create our own custom inventory file in our project directory.

Create a Directory for Ansible Files

First, let's navigate to our project directory and create a dedicated folder for our Ansible files:

cd ~/project
mkdir -p ansible/inventory

Create a Custom Inventory File

Now, let's create a simple inventory file in our new directory:

cat > ansible/inventory/hosts.ini << 'EOF'
## Custom inventory file

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com

[local]
localhost ansible_connection=local

[all:vars]
ansible_user=ubuntu
EOF

This inventory file defines three groups:

  • webservers: Contains two web servers
  • dbservers: Contains two database servers
  • local: Contains localhost with a special connection setting

Let's check our newly created inventory file:

cat ansible/inventory/hosts.ini

You should see the content we just created.

This file is now ready to be used as our custom inventory file. In the next step, we'll configure Ansible to use this file by default instead of the system-wide /etc/ansible/hosts file.

Setting the Default Inventory File Path

Now that we have created our custom inventory file, let's configure Ansible to use it as the default inventory file. There are several ways to do this, but we'll focus on the two most common methods.

Method 1: Using an Ansible Configuration File

Ansible looks for configuration files in the following order:

  1. ANSIBLE_CONFIG environment variable
  2. ansible.cfg in the current directory
  3. ~/.ansible.cfg (user's home directory)
  4. /etc/ansible/ansible.cfg (system-wide)

Let's create an ansible.cfg file in our project directory:

cat > ~/project/ansible/ansible.cfg << 'EOF'
[defaults]
inventory = ~/project/ansible/inventory/hosts.ini
host_key_checking = False
EOF

In this configuration file, we've set:

  • inventory: The path to our custom inventory file
  • host_key_checking: Disabled to prevent SSH host key verification prompts

Method 2: Using an Environment Variable

Another way to specify the inventory file is by using the ANSIBLE_INVENTORY environment variable. This is useful when you want to temporarily use a different inventory file without changing the configuration:

export ANSIBLE_INVENTORY=~/project/ansible/inventory/hosts.ini

Let's confirm that our configuration is working by running a simple Ansible command:

cd ~/project/ansible
ansible --list-hosts all

This command should list all hosts from our custom inventory file:

  hosts (5):
    web1.example.com
    web2.example.com
    db1.example.com
    db2.example.com
    localhost

Now Ansible will use our custom inventory file by default when we run Ansible commands from the ~/project/ansible directory.

Verifying the Inventory Configuration

Now that we've configured our custom inventory file, let's verify that Ansible is using it correctly and explore some commands to work with the inventory.

Checking the Inventory with ansible-inventory

The ansible-inventory command allows us to view and validate our inventory configuration:

cd ~/project/ansible
ansible-inventory --list

This will display the inventory in JSON format:

{
  "_meta": {
    "hostvars": {
      "localhost": {
        "ansible_connection": "local"
      }
    }
  },
  "all": {
    "children": ["dbservers", "local", "ungrouped", "webservers"]
  },
  "dbservers": {
    "hosts": ["db1.example.com", "db2.example.com"]
  },
  "local": {
    "hosts": ["localhost"]
  },
  "webservers": {
    "hosts": ["web1.example.com", "web2.example.com"]
  }
}

For a more readable format, we can use the --graph option:

ansible-inventory --graph

This will show the inventory in a tree-like structure:

@all:
  |--@dbservers:
  |  |--db1.example.com
  |  |--db2.example.com
  |--@local:
  |  |--localhost
  |--@ungrouped:
  |--@webservers:
  |  |--web1.example.com
  |  |--web2.example.com

Testing the Connection to Local Host

Let's run a simple ping command to verify that we can communicate with the local host:

ansible local -m ping

You should see output similar to:

localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

Running a Simple Command on Hosts

We can also run a command on our hosts using the ansible command. Since our example hosts don't actually exist, let's target only the local host:

ansible local -a "uname -a"

This will execute the uname -a command on the local host and show output similar to:

localhost | CHANGED | rc=0 >>
Linux ubuntu 5.15.0-1033-aws #37-Ubuntu SMP Wed Aug 16 07:38:46 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

This confirms that Ansible is correctly using our custom inventory file and can execute commands on the hosts defined in it.

Summary

In this tutorial, you learned how to set up and configure a custom inventory file path in Ansible. You now understand:

  • What an Ansible inventory file is and its default location
  • How to create a custom inventory file with host groups
  • How to configure Ansible to use your custom inventory file by default using both the configuration file method and environment variables
  • How to verify your inventory configuration using various Ansible commands

These skills will help you organize your Ansible automation workflow more efficiently. By customizing the inventory file location, you can better manage your infrastructure based on your project's structure and requirements.

When working on larger projects, you might want to explore dynamic inventories or use Ansible Vault to secure sensitive information in your inventory files.