如何在Ansible Playbook的for循环中直接调用Python处理数据?
问题描述
我开发了一个Ansible Playbook,用于发送包含一组3位补零数字的邮件。需要在邮件正文的for循环中对从变量hostvars[host]['number']获取的数字完成补零操作,目前通过Ansible语法myhost-{{ '%03d' % hostvars[host]['number']|int }}实现了需求。
现在想改用Python的方式处理该补零操作(后续还需对循环输出的每个元素执行更多格式化操作),尝试了两种写法均报错:
- 尝试
{{ "myhost-" + str(hostvars[host]['number']).zfill(3) }},报错:localhost failed | msg: The task includes an option with an undefined variable. The error was: 'str' is undefined - 尝试
myhost-{{ hostvars[host].number.zfill(3) }},报错:localhost failed: {"msg": "The task includes an option with an undefined variable. The error was: 'int object' has no attribute 'zfill'}
需求:在for循环中直接使用Python风格的处理逻辑,而非Ansible原生格式化语法,且不提前在Python中定义变量再代入邮件正文。
原Playbook任务片段:
- 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
解决方案
方法1:使用string过滤器转字符串后调用zfill
Jinja2模板中不能直接使用Python内置的str()函数,需用string过滤器将整数转为字符串,再调用zfill()方法补零:
myhost-{{ hostvars[host]['number'] | string | zfill(3) }}
方法2:使用format过滤器(Python风格格式化)
通过Jinja2的format过滤器,使用Python风格的格式字符串实现补零:
myhost-{{ "{:03d}".format(hostvars[host]['number']|int) }}
修改后的完整Playbook任务片段
- 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-{{ hostvars[host]['number'] | string | zfill(3) }} <br> {% endfor %} <br>text <br>closure
内容的提问来源于stack exchange,提问作者Tms91
相关产品推荐
相关产品推荐

