DEV Community

Cover image for Mastering Ansible Groups Inventory
Labby for LabEx

Posted on

Mastering Ansible Groups Inventory

Introduction

MindMap

In Ansible, an inventory file defines the groups and hosts that Ansible can manage. In this lab, you will learn how to create and configure Ansible groups in the inventory file. Each step will introduce new concepts and gradually build upon the previous steps, helping you understand the group hierarchy and how to target specific hosts.

Setting up SSH

Ansible communicates with managed systems over SSH. In this step, we will configure SSH access to the target system.

Ensure that the target system has SSH server installed and running.
Generate an SSH key pair on the machine where Ansible is installed (if not already done):

ssh-keygen -t rsa -b 4096 -C "joker@labex.io"
Enter fullscreen mode Exit fullscreen mode

This command generates an RSA key pair with a specified email address.
Example output:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/labex/.ssh/id_rsa):
Created directory '/home/labex/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/labex/.ssh/id_rsa
Your public key has been saved in /home/labex/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:WFykSv1i+u1shKTqKtxZOLyZvJM1EPrv3mcDR7FKkak joker@labex.io
The key's randomart image is:
+---[RSA 4096]----+
|        o.o      |
|   .   * +       |
|  . . o * o      |
| . . E =.+       |
|  o o +oS..      |
|   = +.=.o.      |
|. o @.o o.       |
|.. X.... *.      |
| ..+*o .+o=      |
+----[SHA256]-----+
Enter fullscreen mode Exit fullscreen mode

Get the password for the target system's user called labex.

env | grep PASSWORD
Enter fullscreen mode Exit fullscreen mode

Example output:

CHANGE_PASSWORD=true
PASSWORD=lwUiKa41
Enter fullscreen mode Exit fullscreen mode

Tips: If you can't get the password, execute it from the VNC terminal.

Copy the public key (~/.ssh/id_rsa.pub) to the target system:

ssh-copy-id labex@hostname
Enter fullscreen mode Exit fullscreen mode

For example:

ssh-copy-id labex@localhost
Enter fullscreen mode Exit fullscreen mode

This command prompts for the password for the target system's user.
Example output:

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/labex/.ssh/id_rsa.pub"
The authenticity of host 'localhost (localhost)' can't be established.
ED25519 key fingerprint is SHA256:oWrPCo9cmms/tKZl2acSXupNKN3vVRGi1FcQLyjufgI.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
labex@localhost's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'labex@localhost'"
and check to make sure that only the key(s) you wanted were added.
Enter fullscreen mode Exit fullscreen mode

Enter the password for the target system's user when prompted.
Verify SSH connectivity by connecting to the target system:

ssh labex@hostname
Enter fullscreen mode Exit fullscreen mode

For example:

ssh labex@localhost
Enter fullscreen mode Exit fullscreen mode

If you can successfully connect without entering a password, SSH setup is complete.
Example output:

Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.4.0-162-generic x86_64)

* Documentation:  https://help.ubuntu.com
* Management:     https://landscape.canonical.com
* Support:        https://ubuntu.com/pro
Last login: Thu Mar  7 02:10:44 2024 from 47.88.86.45
labex:~/ $
Enter fullscreen mode Exit fullscreen mode

Creating a Basic Inventory

In this step, you will create a basic inventory file and define some hosts without any group configuration.

First, create a new file named inventory using a text editor at /home/labex/project path.
Add the following content to the file, listing the hostnames or IP addresses of your choice:

172.19.0.4
Enter fullscreen mode Exit fullscreen mode

Then, use ansible's ping module to detect the status of hosts.

ansible -i inventory -m ping all
Enter fullscreen mode Exit fullscreen mode
  • ansible: This is the command line tool for Ansible, used to perform various operations such as deployment, configuration management, etc.
  • -i inventory: This part specifies the path to the Ansible inventory file, which contains information about hosts and host groups to let Ansible know where to perform operations.
  • -m ping: This part specifies the Ansible module to be executed, in this case, the ping module, which is used to check if hosts are reachable.
  • all: This part specifies the target hosts or host groups, where all indicates all hosts defined in the inventory file.

Example output:

...
172.19.0.4 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
Enter fullscreen mode Exit fullscreen mode

Grouping Hosts

Groups in the Ansible inventory file allow you to organize hosts based on common characteristics or roles. In this step, you will group the hosts defined in Step 2.

First, open the inventory file created in Step2:Creating a Basic Inventory using a text editor.
Add the following content to the file, defining a group named [web] and adding the hosts to it:

[web]
172.19.0.4
Enter fullscreen mode Exit fullscreen mode
  • [web]: This section defines a host group named web, which includes a host with the IP address 172.19.0.4. This group is typically used to identify a set of hosts with similar configurations or functions.

Then, use ansible's ping module to detect the status of hosts under the web group in the inventory file.

ansible -i inventory -m ping web
Enter fullscreen mode Exit fullscreen mode

Example output:

...
172.19.0.4 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
Enter fullscreen mode Exit fullscreen mode

Subgrouping and Group Hierarchy

Groups can be organized in a hierarchical structure in the Ansible inventory. In this step, you will create subgroups and understand how to represent the group hierarchy.

First, open the inventory file created in Step3:Grouping Hosts using a text editor.
Add the following content to the file, and creating a group [prod] that includes the [web] groups:

[web]
172.19.0.4

[prod:children]
web
Enter fullscreen mode Exit fullscreen mode
  • [prod:children]: In this section, a group named prod is defined as the parent group of the web subgroup. This hierarchical structure helps organize and manage different types of hosts.

Then, use ansible's ping module to detect the status of hosts under the prod group in the inventory file.

ansible -i inventory -m ping prod
Enter fullscreen mode Exit fullscreen mode

Example output:

...
172.19.0.4 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
Enter fullscreen mode Exit fullscreen mode

Variable Assignments to Groups

Variables can be assigned to groups in the Ansible inventory file, allowing you to define group-specific settings or configurations. In this step, you will assign variables to groups in the inventory file.

First, open the inventory file created in Step4:Subgrouping and Group Hierarchy using a text editor.
Add the following content to the file, assigning variable http_port to the [web] group, respectively:

[web]
172.19.0.4

[prod:children]
web

[web:vars]
http_port=80
Enter fullscreen mode Exit fullscreen mode
  • [web:vars]: Here, a variable named http_port is defined with a value of 80. This variable is commonly used to specify the HTTP port for applications within the host group, facilitating deployment of applications or server configuration.

Then, create a new Ansible playbook file called /home/labex/project/check_http_port.yml and open it in a text editor.
Add the following content to the playbook file:

---
- name: Check if http_port variable is defined
  hosts: web
  tasks:
    - name: Debug http_port variable
      debug:
        msg: "The http_port is {{ http_port }}"
Enter fullscreen mode Exit fullscreen mode

When this playbook is executed, it will display a message indicating the value of the http_port variable for hosts in the web group, helping to verify if the variable is correctly defined in the configuration.

Finally, run the playbook with the following command:

ansible-playbook -i inventory check_http_port.yml
Enter fullscreen mode Exit fullscreen mode

Example output:

PLAY [Check if http_port variable is defined] **********************************

TASK [Gathering Facts] *********************************************************
...
ok: [172.19.0.4]

TASK [Debug http_port variable] ************************************************
ok: [172.20.0.5] => {
    "msg": "The http_port is 80"
}

PLAY RECAP *********************************************************************
172.19.0.4                 : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Enter fullscreen mode Exit fullscreen mode

The 80 in "msg": "The http_port is 80" is the value of the http_port we defined in the inventory file.

Summary

Congratulations! You have successfully completed the Ansible groups inventory lab. You have learned how to create and configure groups, create subgroups and define group hierarchy, assign variables to groups, and target specific groups and hosts in your inventory. These skills are essential for organizing your inventory and effectively managing your infrastructure with Ansible. Keep exploring the capabilities of Ansible to further enhance your automation workflows. Happy automating!


🚀 Practice Now: Ansible Groups Inventory


Want to Learn More?

Top comments (0)