如果电子邮件任务失败,您可以使用阻止错误处理将文件保留在原位。例如:
- 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."
这将在一个块中同时运行电子邮件和临时文件删除任务。如果其中一个失败,它将进入救援部分,跳过删除文件,并打印一条调试消息,说明由于失败,文件保留在原位。
关键是使用阻塞和救援来定义一组共同成功或失败的任务。通过这种方式,您可以对失败采取有条件的操作。