Ansible playbook to send mail at the end of completion
Here is an example Ansible playbook that sends an email at the end of completion:
---
- name: Example playbook
hosts: localhost
become: yes
tasks:
- name: Install package
apt:
name: nginx
state: present
- name: Start service
service:
name: nginx
state: started
enabled: yes
handlers:
- name: Send email
mail:
subject: Ansible playbook completed
body: The playbook has completed successfully
from: [email protected]
to: [email protected]
In this example, the playbook installs the nginx
package and starts the nginx
service. The handlers
section defines a handler named Send email
that sends an email using the mail
module.
To use this playbook, save it to a file (e.g. example.yml
) and then run it using the following command:
ansible-playbook -i <hosts_file> example.yml
Replace <hosts_file>
with the path to your Ansible hosts file.
When you run the playbook, Ansible will execute the tasks and then trigger the Send email
handler at the end of the playbook. The email will be sent to the specified recipient with the subject and body specified in the playbook.
You can customize the email settings by modifying the mail
module options. For example, you can add a CC recipient by specifying the cc
option:
handlers:
- name: Send email
mail:
subject: Ansible playbook completed
body: The playbook has completed successfully
from: [email protected]
to: [email protected]
cc: [email protected]
You can also use environment variables to customize the email settings. For example, you can set the MAIL_FROM
and MAIL_TO
environment variables to specify the sender and recipient email addresses:
handlers:
- name: Send email
mail:
subject: Ansible playbook completed
body: The playbook has completed successfully
from: "{{ MAIL_FROM }}"
to: "{{ MAIL_TO }}"
Make sure to set the environment variables before running the playbook:
[email protected] [email protected] ansible-playbook -i <hosts_file> example.yml