I have created an Ansbile script to check uptime of Remote Servers (nearly 60+ servers in a inventory group linux) and to send it to email with CSV and HTML file. It's working but its sending seperate mail for each server.
I need it to gather the output and send a single mail with all server uptime and hostname in csv and HTML.
Here is my script.
main.yaml
---
- name: Generate Uptime HTML Report and Send Email
hosts: linux
gather_facts: true
vars:
email_subject: Uptime Report
email_host: xyz
email_from: xyz
email_to: xyz
email_body_template: templates/report.html.j2
csv_path: /tmp
csv_filename: report.csv
headers: Hostname,Uptime_In_Days
tasks:
- name: Get Uptime
command: uptime
register: uptime_result
- name: Extract Uptime in Days
set_fact:
uptime_days: "{{ uptime_result.stdout | regex_replace('^.*up ([0-9]+) day.*', '\\1') | int }}"
when: uptime_result.rc == 0
- name: Create CSV Data
set_fact:
csv_data:
- Hostname: "{{ inventory_hostname }}"
Uptime_In_Days: "{{ uptime_days }}"
when: uptime_result.rc == 0
- name: Transfer CSV Data File
copy:
content: "{{ csv_data | to_nice_json }}"
dest: "{{ csv_path }}/{{ csv_filename }}"
mode: '0644'
- name: Send Email
mail:
host: "{{ email_host }}"
from: "{{ email_from }}"
to: "{{ email_to }}"
subject: "[Ansible] {{ email_subject }}"
body: "{{ lookup('template', email_body_template) }}"
attach: "{{ csv_path }}/{{ csv_filename }}"
subtype: html
html.j2
<sub><table style="border: 1px solid black; border-collapse: collapse;">
<tr>
{% for header in headers.split(",") %}
<th style="border: 1px solid black; padding: 8px 16px;">{{ header }}</th>
{% endfor %}
</tr>
{% for host in csv_data %}
<tr>
{% for header in headers.split(",") %}
<td style="border: 1px solid black; padding: 8px 16px;">{{ host[header] }}</td>
{% endfor %}
</tr>
{% endfor %}
</table></sub>
Since you are already
gather_factsin order to have Ansible facts avaibale, it also containansible_uptime_seconds. See the minimal reproducible exampleThere is no need for
commandandset_fact.A CSV report can therefore directly be written on the Control Node for all hosts in the current play.
For How to proceed further? you may have a look into
Similar Q&A
systemdstatus into CSV format