![](/img/trans.png)
[英]Is there a way not to format number in Jinja2 templates using 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:
例如:
- 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.