Skip to content

How to send email using Ansible and Gmail

Avatar photo

https://www.linkedin.com/in/gineesh/ https://twitter.com/GiniGangadharan

As part of your automation jobs, you can implement email notifications from Ansible itself instead of manually drafting and sending emails. Ansible mail module is simple and easy to use for sending email notifications.

In this article, you will learn how to configure your Gmail credential and Ansible to send automated email using the Ansible playbook.

Prepare your Google App Password

Gmail will not allow less secured apps to access the mail service and username + password combination will not work if you have enabled the 2FA (2 Factor Authentication). In such cases, you can use the Google App Passwords to programmatically access your Gmail account.

Goto myaccount.google.com -> Click on Security on the left side -> Find and open 2-Step Verification -> Find and open App Passwords.

Select App Passwords and you will reach another window. (Google may ask you to enter your password to verify). Create a new App Password by selecting Others from the dropdown selection.

If you cannot find the App Passwords under Signing in to Google; then click the 2-Step verification and you will find it.

Click on GENERATE button and you will receive the App Password. Remember to copy the password as it wont be visible after this screen.

Prepare secret variables

Since the email address and App Password are sensitive, you cannot keep it in plain text format.

Create a secret variable file encrypted with Ansible vault.

$ ansible-vault create vars/smtp_secrets.yml 
New Vault password: 
Confirm New Vault password: 

Add your email address and App password inside

email_smtp_username: '[email protected]'
email_smtp_password: 'secretpassword'

Save the file and exit as usual.

Prepare Ansible playbook content

Create a role for sending email (You can directly use it inside the playbook but try to follow the best practices as you can use the same role for multiple automation jobs).

$ cd roles/
$ ansible-galaxy role init send-email
- Role send-email was created successfully

Add content to roles/send-email/tasks/main.yml

---
- name: Sending notification email
  mail:
    host: "{{ email_smtp_server }}"
    port: "{{ email_smtp_server_port }}"
    secure: try
    from: "{{ email_smtp_from_address }}"
    to: "{{ email_smtp_to_address }}"
    #cc: "{{ email_smtp_cc_address }}"
    subject: "{{ email_smtp_subject }}"
    body: "{{ email_report_body }}"
    #attach:
    #  - "{{ report_file_name }}"
    headers:
      - Reply-To="{{ email_smtp_replyto_address }}"
    username: "{{ email_smtp_username }}"
    password: "{{ email_smtp_password }}"
  delegate_to: localhost

Create Ansible playbook as below.

---
- name: Ansible mail notification
  hosts: localhost
  gather_facts: no
  vars_files:
    vars/smtp_secrets.yml
  vars:
    email_smtp_server: 'smtp.gmail.com'
    email_smtp_server_port: '587'
    email_smtp_from_address: '[email protected] (Ansible Automation)'
    email_smtp_to_address:
          - 'John Doe <john@gmail.com>'
    #email_smtp_cc_address:
    #      - 'John Doe <[email protected]>'
    email_smtp_replyto_address: '[email protected]'
    email_report_body: "This is a demo email. Check demo attachment."
    email_smtp_subject: "Ansible Email Notification - Demo"
    report_file_name: ./demo-file.txt
  tasks:
    - name: Email notification
      include_role:
        name: send-email

Remember to use appropriate email address, attachments and other details as needed.

Execute the playbook.

$ ansible-playbook ansible-email.yml --ask-vault-password
Vault password: 

PLAY [Ansible mail notification] *******************************************************************

TASK [Email notification] **************************************************************************

TASK [send-email : Sending notification email] *****************************************************
ok: [localhost -> localhost]

PLAY RECAP *****************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Verify the email received in your inbox.

You can enhance the playbook with more validations, format and other functionalities.

Also, remember to delete the Google App Password entry if you are not using it.

Refer to the ginigangadharan/ansible-real-life/ansible-email repository for original playbook content explained above.

Disclaimer:

The views expressed and the content shared in all published articles on this website are solely those of the respective authors, and they do not necessarily reflect the views of the author’s employer or the techbeatly platform. We strive to ensure the accuracy and validity of the content published on our website. However, we cannot guarantee the absolute correctness or completeness of the information provided. It is the responsibility of the readers and users of this website to verify the accuracy and appropriateness of any information or opinions expressed within the articles. If you come across any content that you believe to be incorrect or invalid, please contact us immediately so that we can address the issue promptly.

Avatar photo


https://www.linkedin.com/in/gineesh/ https://twitter.com/GiniGangadharan
Gineesh Madapparambath is the founder of techbeatly and he is the author of the book - ๐—”๐—ป๐˜€๐—ถ๐—ฏ๐—น๐—ฒ ๐—ณ๐—ผ๐—ฟ ๐—ฅ๐—ฒ๐—ฎ๐—น-๐—Ÿ๐—ถ๐—ณ๐—ฒ ๐—”๐˜‚๐˜๐—ผ๐—บ๐—ฎ๐˜๐—ถ๐—ผ๐—ป. He has worked as a Systems Engineer, Automation Specialist, and content author. His primary focus is on Ansible Automation, Containerisation (OpenShift & Kubernetes), and Infrastructure as Code (Terraform). (aka Gini Gangadharan - iamgini.com)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.