提问人:Lesley L 提问时间:7/25/2023 更新时间:7/25/2023 访问量:23
通过电子邮件发送临时文件后如何删除临时文件
How to remove a temp file after emailing it
问:
我想在成功通过电子邮件发送临时文件后将其删除,但如果电子邮件任务失败,请将其保留在原位。
这是我的任务:
- 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服务器关闭或配置错误,则可能会发生这种情况,在这种情况下,我可能需要通过其他方法获取文件。也许有一种方法可以将“正常”状态视为“已更改”?
答:
1赞
itsmedannyc
7/25/2023
#1
如果电子邮件任务失败,您可以使用阻止错误处理将文件保留在原位。例如:
- 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."
这将在一个块中同时运行电子邮件和临时文件删除任务。如果其中任何一个失败,它将命中救援部分并跳过删除文件,并打印一条调试消息,指出文件由于失败而留在原位。
关键是使用阻止和救援来定义一组同时成功或失败的任务。这样,您就可以对失败采取有条件的操作。
评论
0赞
Lesley L
7/25/2023
谢谢!这应该可以解决我的问题。
0赞
itsmedannyc
7/25/2023
没关系!很高兴它能帮到你
评论