Ansible:仅当满足每个附件的相应条件时才向电子邮件添加许多附件

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

this thread 中,解释了如何仅在满足条件时才将单个附件添加到通过 community.general.mail 模块 发送的邮件中。

现在,如果满足某些(=“他们的”)各自的条件,我想从附件列表中添加许多文件作为附件。

我尝试通过定义要附加的文件列表来做到这一点

list_of_attachments_paths: 
  "{% set attachments_list = [] %}
  {% if NOL_in_file1.stdout|int > 0  %}
  {{ attachments_list.append( file1_path ) }}
  {% endif %}
  {% if NOL_in_file2.stdout|int > 0  %}
  {{ attachments_list.append( file2_path ) }}
  {% endif %}
  {{ attachments_list }}"

调试任务

    - name: show list_of_attachments_paths
      debug:
        msg: 
          - "{{ list_of_attachments_paths }}"

这是发送邮件的任务

- name: Send the analysis via e-mail 
  community.general.mail:

    subtype: html  
    host: smtp.myserver.it
    port: 25
    sender: [email protected]
    to:
      "{{ mail_to_recipients }}"
    cc:
      "{{ mail_cc_recipients }}"


    subject: "[automated-sender] my analysis"
    attach:
      - "{{ list_of_attachments_paths }}"

    body: "{{ body_analysis }}"

调试任务返回:

show list_of_attachments_paths...   
  localhost ok: {    
    "changed": false,    
    "msg": [    
        "       ['/home/myuser/mypath/file1.csv', '/home/myuser/mypath/file2.csv']"

    ]

}

但我收到此错误,但我不明白为什么

Send the report via e-mail...

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: FileNotFoundError: [Errno 2] No such file or directory: "       ['/home/myuser/mypath/file1.csv'"

  localhost failed | msg: Failed to send community.general.mail: can't attach file        ['/home/myuser/mypath/file1.csv': [Errno 2] No such file or directory: "       ['/home/myuser/mypath/file1.csv'"

任务密钥的ansible文档

attach
中明确指出输入必须是附件路径列表,那么这里有什么问题?

list ansible jinja2
1个回答
0
投票

我找到了一个(非常糟糕的)方法来解决问题:

    - name: Generate void list of attachment paths
      set_fact:
        list_of_attachments_paths: "{{ [] }}"


    - name: Update list of attachment paths - file1
      when: NOL_in_file1.stdout|int > 0
      set_fact:
        list_of_attachments_paths: "{{ list_of_attachments_paths + [file1_path]  }}"


    - name: Update list of attachment paths - file2
      when: NOL_in_file2.stdout|int > 0
      set_fact:
        list_of_attachments_paths: "{{ list_of_attachments_paths + [file2_path]  }}"

然后

- name: Send the analysis via e-mail 
  community.general.mail:

    subtype: html  
    host: smtp.myserver.it
    port: 25
    sender: [email protected]
    to:
      "{{ mail_to_recipients }}"
    cc:
      "{{ mail_cc_recipients }}"


    subject: "[automated-sender] my analysis"
    attach:
      "{{ list_of_attachments_paths | select('defined') | list }}"  # note the select('defined) filter

    body: "{{ body_analysis }}"
© www.soinside.com 2019 - 2024. All rights reserved.