To create an Ansible playbook that:
Before implementing this project, ensure you have:
Ansible uses an inventory file to define hosts and groups.
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.
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 }}"
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.
Edit the Ansible configuration file (ansible.cfg) to use the custom inventory.
[defaults]
inventory = inventory.ini
host_key_checking = False
Execute the playbook to test connectivity and check uptime.
ansible-playbook -i inventory.ini ping_uptime.yml
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"
}
cron
or Ansible Tower
.This project is a fundamental step in learning Ansible automation.