Hello Guys,
Recently while working on one of the projects, I have to send an Email notification .Sending an Email is an Easy in Ansible one can use mail (community.general.mail) module to do it but what if we have to send an formatted Email or lets say an Html email
We can chive the same with the help of jinja template , file lookup plugin and mail module in ansible
the code for which will look like this
create a file called alert_email.html.j2
[root@aap1 Email]# cat alert_email.html.j2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Failed {{ job_id }}</title>
</head>
<body>
<p>Dear Team,</p>
<p>This is an automated alert to inform you about the following issue:</p>
<ul>
<li><strong>Failing Job: </strong> {{ job_id }} </li>
<li><strong>Details: </strong> {{ issue_description }} </li>
</ul>
<p>Please take necessary actions to address this issue promptly.</p>
<p>Best regards,<br/>{{ user_email }}</p>
</body>
</html>
sendmail.yml
---
- name: Send HTML email alert
hosts: localhost
vars_files:
- var1.yml
vars:
job_id: 115
user_email: "nrathi@example.com"
issue_description: "The server is down and requires immediate attention."
tasks:
- name: Include Jinja template for email body
template:
src: alert_email.html.j2
dest: /tmp/alert_email.html
- name: Send email Alert
mail:
host: smtp.gmail.com
port: 587
subtype: html
to:
- "{{ to }}"
subject: "Alert: {{ job_id }}"
subtype: html
body: "{{ lookup('file', '/tmp/alert_email.html') }}"
username: "{{ uname }}"
password: "{{ pass }}"
and in var1.yml file contains your smtp username, password and recipient list
This is the final outcome