Tuesday, September 21, 2021

Ansible Playbook to collect uptime of servers

Hi, 

This is to explain how we can write a small playbook to collect uptime of all servers in our environment. We can use our own server list or group name as referred in Ansible Inventory. Here I used "infra_redhat" which is already defined in Ansible Inventory.

We can also mention the mail Id to which we need to recieve uptime report. 

With this playbook, we are running in a jumphost or some admin server from where, all servers are connected. 

We are just collecting outout of "uptime" command and saving a small CSV file. 

- name: Checking the server  uptime
  hosts: infra_redhat
  gather_facts: no
  tasks:
  - name: Create the server uptime report
    copy:
      content: Server Name, Uptime
      dest: /var/tmp/serveruptime.csv
    delegate_to: localhost

  - name: getting the uptime of mysql
    shell: uptime
    register: output_uptime
    changed_when: "output_uptime.rc != 0"
  - name:
    set_fact:
      UPTIME: "{{ output_uptime.stdout | replace('\t','') }}"
  - name: display the message
    lineinfile:
      line: "{{ inventory_hostname }},{{ UPTIME }}"
      insertafter: EOF
      path: /var/tmp/serveruptime.csv
    delegate_to: localhost

- name: Mail uptime report
  hosts: localhost
  tasks:
  - name: server uptime mail
    mail:
      subject: Server uptime report
      body: Hi, Please find attached server uptime report
      to:
      - root@localhost
      attach:
      - /var/tmp/serveruptime.csv


 Once this is run, we get good output in CSV format like follows, 

 $ cat /var/tmp/serveruptime.csv 
Server Name, Uptime 
server1, 04:00:20 up 38 days, 13:12, 1 user, load average: 0.42, 1.38, 0.87 
server2, 04:00:18 up 38 days, 14:33, 1 user, load average: 0.00, 0.07, 0.13 
server3, 04:00:20 up 39 days, 13:14, 1 user, load average: 0.04, 0.74, 0.79


Ansible Playbook to collect uptime of servers

Hi,  This is to explain how we can write a small playbook to collect uptime of all servers in our environment. We can use our own server l...