Ansible Groups Inventory

AnsibleAnsibleBeginner
Practice Now

Introduction

In this lab, you will learn how to create and configure Ansible inventory files. Ansible uses inventory files to define and organize the hosts it manages. You will explore the basic structure of an inventory file, create groups, establish group hierarchies, and assign variables to groups. These skills are essential for effectively managing your infrastructure with Ansible.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/RemoteAccessandNetworkingGroup(["`Remote Access and Networking`"]) linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) ansible(("`Ansible`")) -.-> ansible/AnsibleSetupandConfigurationGroup(["`Ansible Setup and Configuration`"]) ansible(("`Ansible`")) -.-> ansible/InventoryManagementGroup(["`Inventory Management`"]) ansible(("`Ansible`")) -.-> ansible/ModuleOperationsGroup(["`Module Operations`"]) linux/RemoteAccessandNetworkingGroup -.-> linux/ssh("`Secure Connecting`") linux/VersionControlandTextEditorsGroup -.-> linux/vim("`Text Editing`") linux/VersionControlandTextEditorsGroup -.-> linux/nano("`Simple Text Editing`") ansible/AnsibleSetupandConfigurationGroup -.-> ansible/install("`Ansible Setup`") ansible/InventoryManagementGroup -.-> ansible/groups_inventory("`Define Inventory Groups`") ansible/ModuleOperationsGroup -.-> ansible/ping("`Network Test`") subgraph Lab Skills linux/ssh -.-> lab-290160{{"`Ansible Groups Inventory`"}} linux/vim -.-> lab-290160{{"`Ansible Groups Inventory`"}} linux/nano -.-> lab-290160{{"`Ansible Groups Inventory`"}} ansible/install -.-> lab-290160{{"`Ansible Groups Inventory`"}} ansible/groups_inventory -.-> lab-290160{{"`Ansible Groups Inventory`"}} ansible/ping -.-> lab-290160{{"`Ansible Groups Inventory`"}} end

Creating a Basic Inventory

The lab environment has been pre-configured with SSH access to the local machine. You can use localhost as the target host for all Ansible operations in this lab.

An Ansible inventory file defines the hosts and groups of hosts upon which commands, modules, and tasks in a playbook operate. Let's create a basic inventory file.

Create a new file named inventory in the /home/labex/project directory:

nano /home/labex/project/inventory

Add the following content to the file:

localhost ansible_connection=local

Let's break this down:

  • localhost: This is the name of the host. In this case, it's the local machine.
  • ansible_connection=local: This is an Ansible variable that tells Ansible to connect to this host locally, rather than via SSH. This is useful for managing the local machine.

Save the file and exit the editor (in nano, press Ctrl+X, then Y, then Enter).

Now, let's test our inventory using Ansible's ping module. The ping module doesn't actually use the ICMP ping protocol; instead, it verifies that Ansible can connect to the host and execute Python code.

Run this command:

ansible -i inventory -m ping all

Let's break down this command:

  • -i inventory: Specifies the inventory file to use.
  • -m ping: Tells Ansible to use the ping module.
  • all: Targets all hosts in the inventory.

You should see output indicating a successful connection:

localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

If you see this output, it means Ansible successfully connected to the localhost and executed the ping module.

Grouping Hosts

Ansible allows you to organize hosts into groups. This is useful for applying configurations or running tasks on multiple hosts simultaneously. Let's modify our inventory to include a group.

Edit the inventory file:

nano /home/labex/project/inventory

Update the content to:

[webservers]
localhost ansible_connection=local

This defines a group called webservers that includes our localhost. In Ansible, groups are defined by putting the group name in square brackets []. Any hosts listed under a group belong to that group.

Save and exit the editor.

Now, let's test our group using the ping module:

ansible -i inventory -m ping webservers

This command is similar to the previous one, but instead of all, we're targeting the webservers group.

You should see the same successful output as before, but now we're explicitly targeting the webservers group. This might seem unnecessary with only one host, but as your inventory grows, grouping becomes increasingly useful for targeting specific sets of hosts.

Creating Group Hierarchies

Ansible supports nested groups, allowing you to create hierarchies. This is useful for organizing hosts based on their roles or environments. Let's add another group and create a hierarchy.

Edit the inventory file:

nano /home/labex/project/inventory

Update the content to:

[webservers]
localhost ansible_connection=local

[production:children]
webservers

This creates a new group called production that includes all hosts in the webservers group. The :children suffix tells Ansible that this group is a group of groups, not a group of hosts.

Here's what this hierarchy means:

  • Any host in the webservers group is also implicitly in the production group.
  • You can apply configurations to all production hosts by targeting the production group.
  • You can still target just the webservers if needed.

Save and exit the editor.

Test the new group hierarchy:

ansible -i inventory -m ping production

This command should ping all hosts in the production group, which includes all hosts in the webservers group. In our case, it's still just the localhost, but in a real-world scenario, this structure allows for powerful and flexible host management.

Assigning Variables to Groups

Ansible allows you to assign variables to groups in the inventory file. These variables can be used in playbooks and templates, making your Ansible code more flexible and reusable.

Edit the inventory file:

nano /home/labex/project/inventory

Update the content to:

[webservers]
localhost ansible_connection=local

[production:children]
webservers

[webservers:vars]
http_port=80

This assigns the variable http_port with a value of 80 to all hosts in the webservers group. The :vars suffix is used to define variables for a group.

Save and exit the editor.

Now, let's create a simple playbook to display this variable. A playbook is a YAML file that defines a set of tasks to be executed on hosts. Create a new file named show_http_port.yml:

nano /home/labex/project/show_http_port.yml

Add the following content:

---
- name: Show HTTP Port
  hosts: webservers
  tasks:
    - name: Display HTTP Port
      debug:
        msg: "The HTTP port is {{ http_port }}"

This playbook:

  • Targets the webservers group
  • Has a single task that uses the debug module to display a message
  • Uses the {{ http_port }} syntax to reference the variable we defined in the inventory

Save and exit the editor.

Run the playbook:

ansible-playbook -i inventory show_http_port.yml

You should see output displaying the HTTP port value:

PLAY [Show HTTP Port] ********************************************************

TASK [Gathering Facts] ********************************************************
ok: [localhost]

TASK [Display HTTP Port] ******************************************************
ok: [localhost] => {
    "msg": "The HTTP port is 80"
}

PLAY RECAP ********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

This demonstrates that the variable we defined in the inventory is accessible in our playbook.

Summary

In this lab, you have learned the fundamentals of Ansible inventory management. You created a basic inventory file and learned how to use the Ansible ping module to verify connectivity. You explored how to group hosts and create group hierarchies, which are essential for organizing and managing larger infrastructures. Finally, you learned how to assign variables to groups and use them in a simple playbook.

These skills form the foundation of working with Ansible and will be invaluable as you move on to more complex automation tasks. Remember that effective inventory management is key to scalable and maintainable Ansible projects. As you continue your Ansible journey, consider exploring more advanced inventory features such as dynamic inventories and inventory plugins.

Practice is key to mastering these concepts. Try creating more complex inventories, experiment with different group structures, and use variables in more advanced playbooks. The more you work with Ansible, the more comfortable you'll become with its powerful automation capabilities.

Other Ansible Tutorials you may like