[英]How to run Ansible Module in python with an ansible playbook
[英]How can I call python directly inside Ansible playbook, in a for loop?
我已經開發了一個劇本,它發送一封郵件,指示一個 3-zero-padded 數字的列表。
我想在打印郵件正文信息的 for 循環中進行填充。
該劇本從變量hostvars[host]['number']
中獲取要填充的數字。
填充是通過 Ansible 語法進行的
myhost-{{ '%03d' % hostvars[host]['number']|int }}
正如您在以下任務中看到的那樣。
現在,我想通過 Python 進行填充,因為稍后我想對循環打印的每個元素進行更多格式化操作。
所以我試圖用
{{ "myhost-" + str(hostvars[host]['number']).zfill(3) }}
但我收到此錯誤:
Sending e-mail report...
localhost failed | msg: The task includes an option with an undefined variable. The error was: 'str' is undefined
所以我試着用
myhost-{{ hostvars[host].number.zfill(3) }}
但現在我明白了
Sending e-mail report...
localhost failed: {
"msg": "The task includes an option with an undefined variable. The error was: 'int object' has no attribute 'zfill'
}
那么,我如何在 for 循環中調用 python 來操縱信息以使用 Python 而不是 Ansible 進行打印?
注意:我想在循環中直接調用 python 並且我不想在 python 中定義變量並將它們替換到郵件正文中。
我的劇本的任務:
- name: Sending e-mail report
community.general.mail:
host: myhost
port: 25
sender: mymail
to:
- people@mail.it
subject: "mail of day {{ current_date }}"
subtype: html
body: |
<br>title
<br>text
{% for host in mylist %}
myhost-{{ '%03d' % hostvars[host]['number']|int }}
<br>
{% endfor %}
<br>text
<br>closure
解決了
由於第一次使用內置 python str()
function 引發錯誤,而 python 語法的其他元素沒有引發任何錯誤,我猜測 python 內置函數無法被 Ansible 解釋(我仍然不不明白為什么)。
因此,我查找了一種通過使用 object 的一些 python 方法而不是 python function 的方法來進行數據操作的方法。
因此,我沒有使用str(my_object)
將 int object 轉換為字符串,而是利用了 int python 方法.__str__()
。
所以我用
myhost-{{ hostvars[host].number.__str__().zfill(3) }}
這次成功了。
這讓我覺得不能在 ansible {{ }}
標簽內使用 python 函數,而只能使用 python 對象方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.