Task: Basic Ansible Playbook with Inventory

Objective

To create an Ansible playbook that:

  1. Defines an inventory of hosts.
  2. Pings all hosts to check connectivity.
  3. Checks the uptime of each host.
  4. Provides a structured output of the results.

Task Implementation Steps

1. Prerequisites

Before implementing this project, ensure you have:

2. Setup Inventory File

Ansible uses an inventory file to define hosts and groups.

Step 2.1: Create an Inventory File

Create a file called inventory.ini and define the managed nodes.

[webservers]
web1 ansible_host=192.168.1.10 ansible_user=ubuntu
web2 ansible_host=192.168.1.11 ansible_user=ubuntu

[databases]
db1 ansible_host=192.168.1.20 ansible_user=ubuntu

[webservers] and [databases] are groups.

ansible_host defines the target IP.

ansible_user specifies the SSH user.

3. Write the Ansible Playbook

Create a playbook file named ping_uptime.yml.

---
- name: Ping and check uptime of hosts
  hosts: all
  gather_facts: no
  tasks:

    - name: Ping all hosts
      ansible.builtin.ping:

    - name: Check uptime of hosts
      ansible.builtin.command: uptime
      register: uptime_output

    - name: Display uptime
      ansible.builtin.debug:
        msg: "Uptime for {{ inventory_hostname }}: {{ uptime_output.stdout }}"

Explanation:

Ping Task: Uses the ping module to check connectivity.

Uptime Task: Runs the uptime command to get system uptime.

Debug Task: Displays the output in a readable format.

4. Configure Ansible Hosts File

Edit the Ansible configuration file (ansible.cfg) to use the custom inventory.

[defaults]
inventory = inventory.ini
host_key_checking = False

5. Run the Playbook

Execute the playbook to test connectivity and check uptime.

ansible-playbook -i inventory.ini ping_uptime.yml

6. Expected Output

If everything is configured correctly, you should see output like:

TASK [Ping all hosts] *****************************************************
ok: [web1]
ok: [web2]
ok: [db1]

TASK [Check uptime of hosts] ***********************************************
changed: [web1]
changed: [web2]
changed: [db1]

TASK [Display uptime] ******************************************************
ok: [web1] => {
    "msg": "Uptime for web1: 12:35:46 up 5 days,  4:10,  1 user,  load average: 0.10, 0.05, 0.01"
}
ok: [web2] => {
    "msg": "Uptime for web2: 12:35:46 up 3 days,  2:45,  1 user,  load average: 0.05, 0.02, 0.00"
}
ok: [db1] => {
    "msg": "Uptime for db1: 12:35:46 up 10 days,  8:30,  2 users,  load average: 0.20, 0.10, 0.05"
}

Enhancements and Next Steps

This project is a fundamental step in learning Ansible automation.