Ansible条件触发邮件附件:仅满足条件时添加附件的实现
Ansible邮件任务:仅满足条件时添加附件
问题场景
我正在维护一份第三方编写的Ansible Playbook,执行结束后会发送邮件。需求是仅当Number_of_lines_in_attachment.stdout|int > 0时,才给邮件添加附件。
原任务代码:
- name: Send the analysis via e-mail community.general.mail: subtype: html host: smtp.myserver.it port: 25 sender: automated-sender@myserver.it to: "{{ mail_to_recipients }}" cc: "{{ mail_cc_recipients }}" subject: "[automated-sender] my analysis" attach: - "{{ attachment_path if Number_of_lines_in_attachment.stdout|int > 0 else '' }}" body: "{{ body_analysis }}"
执行后报错:
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: FileNotFoundError: [Errno 2] No such file or directory: '' localhost failed | msg: Failed to send community.general.mail: can't attach file : [Errno 2] No such file or directory: ''
解决方案
方法1:直接控制attach参数的列表内容
当条件满足时传入包含附件路径的列表,否则传入空列表。Ansible会自动忽略空列表的attach参数,不会尝试读取不存在的文件:
- name: Send the analysis via e-mail community.general.mail: subtype: html host: smtp.myserver.it port: 25 sender: automated-sender@myserver.it to: "{{ mail_to_recipients }}" cc: "{{ mail_cc_recipients }}" subject: "[automated-sender] my analysis" attach: "{{ [attachment_path] if Number_of_lines_in_attachment.stdout|int > 0 else [] }}" body: "{{ body_analysis }}"
方法2:用列表过滤实现(适合多附件场景)
如果后续有多个附件需要判断,用列表过滤的方式更灵活,只保留符合条件的路径:
- name: Send the analysis via e-mail community.general.mail: subtype: html host: smtp.myserver.it port: 25 sender: automated-sender@myserver.it to: "{{ mail_to_recipients }}" cc: "{{ mail_cc_recipients }}" subject: "[automated-sender] my analysis" attach: "{{ [attachment_path] | select('defined') if Number_of_lines_in_attachment.stdout|int > 0 else [] }}" body: "{{ body_analysis }}"
方法3:拆分为两个独立任务
如果逻辑复杂,直接拆成两个任务,用when条件控制执行哪一个,逻辑更清晰:
- name: Send analysis via e-mail with attachment community.general.mail: subtype: html host: smtp.myserver.it port: 25 sender: automated-sender@myserver.it to: "{{ mail_to_recipients }}" cc: "{{ mail_cc_recipients }}" subject: "[automated-sender] my analysis" attach: - "{{ attachment_path }}" body: "{{ body_analysis }}" when: Number_of_lines_in_attachment.stdout|int > 0 - name: Send analysis via e-mail without attachment community.general.mail: subtype: html host: smtp.myserver.it port: 25 sender: automated-sender@myserver.it to: "{{ mail_to_recipients }}" cc: "{{ mail_cc_recipients }}" subject: "[automated-sender] my analysis" body: "{{ body_analysis }}" when: Number_of_lines_in_attachment.stdout|int <= 0
内容的提问来源于stack exchange,提问作者Tms91
相关产品推荐
相关产品推荐

