Ansible

Send Emails Using Ansible

Ansible is an open-source IT automation engine that can help you automate the configuration management, application deployment, and even specific security tasks.

In this tutorial, we will discuss how we can use Ansible to send emails which is valuable for notifying the system administrators or teams about the status of specific tasks.

Prerequisites:

  • Installed Ansible
  • Access to an SMTP Server

Setting Up the Email Configurations

To send the emails in Ansible, we use the mail module. Before we can use it, however, we need to do some configurations.

Install the Required Packages

Before we can use this module, we need to install the “smtplib” library. By default, you should have it installed with your default Python environment.

You also need to set up the SMTP server to send emails. You can also use Gmail for testing.

smtp.gmail.com

Requires SSL
: Yes

Requires TLS
: Yes (if available)

Requires Authentication
: Yes

Port for SSL
: 465

Port for TLS/STARTTLS
: 587

Examples:

The following are some basic examples of sending emails using the mail module in Ansible.

Example 1: Basic Usage

The following playbook demonstrates how to use the mail module to send a basic email:

---
- name
: Send email notification
hosts
: localhost
tasks
:
- name
: Sending an email
mail
:
host
: smtp.gmail.com
port
: 587
username
: admin@gmail.com
password
: password
to
: admin@server.admin
subject
: Ansible Email Test
body
: 'This is a test email from Ansible.'
secure
: starttls

Note: Avoid hardcoded passwords in playbook. Consider using the Ansible Vault or environment variables.

Example 2: Including Attachments

We can use the attach parameter as shown in the following to send an email with attachments:

---
- name
: Send email with attachment
hosts
: localhost
tasks
:
- name
: Sending an email
mail
:
host
: smtp.gmail.com
port
: 587
username
: admin@gmail.com
password
: password
to
: admin@server.admin
subject
: Ansible Email with Attachment
body
: 'Please find the attached report.'
attach
: /var/log/apache.log
secure
: starttls

Conclusion

We learned about the Ansible mail module to send emails which makes it easy to notify the relevant users about various system events.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list