Riyad Ali
Riyad Ali

Reputation: 11

How to send email as a condition in Ansible Playbook?

I have created a playbook on Ansible to Yum Update on every Linux Server I have.

I have incorporated the mail module to send an email for every host after the playbook has been completed, even if the server was not updated. I was wondering if it is possible to only send an email to me IF the server was updated so I am only aware of the boxes that were updated?

This is my yaml:

---


- name: yum update for all hosts
  hosts: linux servers
  become: yes
  become_method: su


  tasks:
    - name: yum update
      yum: >
        update_cache=yes
        name=*
        state=latest
        update_cache=yes

    - name: send mail
      mail:
       host: xxx.xxx.xxx.xxx
       port: xxxxxxxx
       sender: [email protected]
       to: Riyad Ali <[email protected]>
       subject: Report for { { ansible_hostname } }
       body: 'Server { { ansible_hostname } } has bene updated'
      delegate_to: localhost

Upvotes: 1

Views: 9467

Answers (2)

JGK
JGK

Reputation: 4168

The method with minimal change would probably be:

---

- name: yum update for all hosts
  hosts: linux servers
  become: yes
  become_method: su

  tasks:
    - name: yum update
      yum:
        update_cache: yes
        name: '*'
        state: latest
        update_cache: yes
      register: yum_update

    - name: send mail
      mail:
        host: xxx.xxx.xxx.xxx
        port: xxxxxxxx
        sender: '[email protected]'
        to: 'Riyad Ali <[email protected]>'
        subject: 'Report for {{ ansible_hostname }}'
        body: 'Server {{ ansible_hostname }} has been updated'
      delegate_to: localhost
      when: yum_update.changed

Upvotes: 0

techraf
techraf

Reputation: 68609

The easiest way is to change your send mail task to be a handler:

tasks:
  - name: yum update
    yum: >
      update_cache=yes
      name=*
      state=latest
      update_cache=yes
    notify: send mail

handlers:
  - name: send mail
      mail:
      host: xxx.xxx.xxx.xxx
      port: xxxxxxxx
      sender: [email protected]
      to: Riyad Ali <[email protected]>
      subject: Report for { { ansible_hostname } }
      body: 'Server { { ansible_hostname } } has bene updated'
    delegate_to: localhost

But you might also consider modifying mail callback plugin to suit your needs.

Upvotes: 0

Related Questions