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

问题描述 投票:0回答:2

我已经在我拥有的每台 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: [email protected]
       to: Riyad Ali <[email protected]>
       subject: Report for { { ansible_hostname } }
       body: 'Server { { ansible_hostname } } has bene updated'
      delegate_to: localhost
ansible conditional-statements ansible-2.x
2个回答
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: [email protected]
      to: Riyad Ali <[email protected]>
      subject: Report for { { ansible_hostname } }
      body: 'Server { { ansible_hostname } } has bene updated'
    delegate_to: localhost

但是您也可以考虑修改

mail
回调插件以满足您的需求。


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: '[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
© www.soinside.com 2019 - 2024. All rights reserved.