繁体   English   中英

是否可以使用 Jinja2 模板在 Ansible 上发送一封包含多个附件的电子邮件

[英]Is it possible to send one email with multiple attachments on Ansible using Jinja2 templates

我的 yml 剧本为其运行的每个主机生成一个文件,然后发送一封包含该文件的电子邮件。 现在,它向每个主机的每个文件发送一封电子邮件,我想知道是否可以将来自多个主机的多个文件附加到同一封电子邮件,我认为 Jinja2 模板是可行的方法。

这是我的 Jinja 模板,我知道我没有正确使用主机循环,因为它没有循环遍历主机,而是运行一个主机然后结束。

{% for host in ansible_play_hosts %}
{% for item in files_to_email.files -%}
{{ item.path }}
{%- endfor %}
{% endfor% }

这是 yml 剧本的相关部分

- name: get the file
  find:
    paths: /mypath
    patterns: '.*yumlist.*'
    use_regex: yes
  register: file_to_email

- name: email files
  mail: 
    from: noreply@test.com
    subject: test
    to:
      -me@myemailaddress
    body: test
    attach:
    - "{{ lookup('template', 'mail_body.j2') }}"
  run_once: true

如果我的文件名分别是主机 1 和主机 2 上的文件 1 和文件 2,我会收到一条错误消息“fatal: [host1]: FAILED: can't attach file /mypath/file1/mypath/file1\n: [Errno 20] Not一个目录,/mypath/file1/mypath/file1\n: rc: 1

甚至懒得看第二位主持人,所以我不知所措。

问: “发送一封包含多个附件的电子邮件。”

A:让我们有一群主人

group2:
  hosts:
    test_01:
    test_02:
    test_03:
  1. 在本地主机上创建一个临时目录
  2. 将所有文件提取到该目录
  3. 创建要附加的文件列表
  4. 发送电子邮件并附上文件列表
  5. 删除临时目录

例如:

- hosts: group2
  tasks:
    - tempfile:
        state: directory
      register: attach_dir
      delegate_to: localhost
      run_once: true

    - fetch:
        dest: "{{ attach_dir.path }}"
        src: /etc/passwd

- hosts: localhost
  tasks:
    - set_fact:
        attach_dir: "{{ hostvars[groups.group2.0]['attach_dir'] }}"
    - find:
        paths: "{{ attach_dir.path }}"
        recurse: true
      register: files_found

    - set_fact:
        files_to_email: "{{ files_found.files|json_query('[].path') }}"

    - mail: 
        from: noreply@localhost
        subject: Ansible test
        to:
          - root@localhost
        body: |
          List of attached files
          {% for file in files_to_email %}
          {{ file }}
          {% endfor %}
        attach: "{{ files_to_email }}"

    - file:
        state: absent
        path: "{{ attach_dir.path }}"

电子邮件应类似于此示例

From: noreply@localhost
To: root@localhost
Cc: 
Subject: Ansible test
Date: Fri, 13 Dec 2019 02:35:19 +0100
X-Mailer: Ansible mail module

List of attached files
/tmp/ansible.kf2wHf/test_01/etc/passwd
/tmp/ansible.kf2wHf/test_02/etc/passwd
/tmp/ansible.kf2wHf/test_03/etc/passwd

[passwd  application/octet-stream (2294 bytes)] 
[passwd  application/octet-stream (2294 bytes)] 
[passwd  application/octet-stream (2294 bytes)] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM