我想在成功通过电子邮件发送临时文件后将其删除,但如果电子邮件任务失败,则将其保留在原处。
这是我的任务:
- name: send email
mail:
host: smtp.example.com
port: 25
from: "{{ emailme }}"
to: "{{ emailme }}"
subject: "initial config script for {{ uppercase_hostname }}"
body: "Here it is"
attach: "{{ tempfilename }}"
notify: remove temp file
changed_when: true
我必须添加“changed_when”,因为当电子邮件成功发送时,邮件模块返回“ok”,因此处理程序通常不会收到通知。但也许电子邮件操作会失败 - 临时文件仍然会被删除。
如果电子邮件任务失败,如何保留文件?如果 SMTP 服务器已关闭或配置错误,则可能会发生这种情况,在这种情况下,我可能需要通过其他方法来获取文件。也许有一种方法可以将“正常”状态视为“已更改”?
如果电子邮件任务失败,您可以使用块错误处理将文件保留在原处。例如:
- name: Send email and conditionally remove temp file
block:
- name: Send email
mail:
host: smtp.example.com
port: 25
from: "{{ emailme }}"
to: "{{ emailme }}"
subject: "Initial config script for {{ uppercase_hostname }}"
body: "Here it is"
attach: "{{ tempfilename }}"
changed_when: true
- name: Remove temp file
file:
path: "{{ tempfilename }}"
state: absent
rescue:
- name: Debug message that file was left due to failure
debug:
msg: "Email failed, leaving {{ tempfilename }} in place."
这将在一个块中一起运行电子邮件和临时文件删除任务。如果其中任何一个失败,它将进入救援部分并跳过删除文件,并打印一条调试消息,表明文件由于失败而保留在原处。
关键是使用block和rescue来定义一组一起成功或一起失败的任务。这样您就可以在失败时采取有条件的操作。