如何在Ansible Playbook中发送电子邮件作为条件?

时间:2018-08-09 11:54:29

标签: ansible conditional ansible-2.x

我在每台拥有的Linux服务器上都创建了有关Ansible to Yum Update的剧本。

我已经合并了邮件模块,以便在剧本完成后向每台主机发送电子邮件,即使服务器没有更新也是如此。 我想知道如果服务器已更新,是否只能向我发送电子邮件,所以我只知道已更新的邮箱?

这是我的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: riyad1504@hotmail.co.uk
       to: Riyad Ali <riyad15044@hotmail.co.uk>
       subject: Report for { { ansible_hostname } }
       body: 'Server { { ansible_hostname } } has bene updated'
      delegate_to: localhost

2 个答案:

答案 0 :(得分:0)

最简单的方法是将send mail任务更改为处理程序:

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: riyad1504@hotmail.co.uk
      to: Riyad Ali <riyad15044@hotmail.co.uk>
      subject: Report for { { ansible_hostname } }
      body: 'Server { { ansible_hostname } } has bene updated'
    delegate_to: localhost

但是您也可以考虑修改mail callback plugin以适合您的需求。

答案 1 :(得分:0)

更改最少的方法可能是:

---

- 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: 'riyad1504@hotmail.co.uk'
        to: 'Riyad Ali <riyad15044@hotmail.co.uk>'
        subject: 'Report for {{ ansible_hostname }}'
        body: 'Server {{ ansible_hostname }} has been updated'
      delegate_to: localhost
      when: yum_update.changed