templates - 迭代 Jinja 模板中的变量
问题描述
我想遍历 ansible yaml 中的变量并在 jinja 模板中添加键和值
多变的:
my:
variable:
- name: test
path: /etc/apt
cert: key.crt
我的模板
{% for key, value in item() %}
{{key}}: {{value}}
{% endfor %}
ansible yaml
- name: test
template:
force: yes
src: test.conf.j2
dest: /tmp/test.conf"
become: yes
with_items:
- "{{ my.variable }}"
我的 yaml 应该是什么样子:
path: /etc/apt
cert: key.crt
解决方案
您的任务中实际上存在三个问题:
使用循环时,可能是
loop
您with_*
访问当前使用变量循环的元素的方式item
,所以不是您在任务中使用的函数(item()
)你正在做一个多余的列表列表
with_items: - "{{ my.variable }}"
第一步是做
with_items: "{{ my.variable }}"
.
一个更好的步骤是使用文档中建议的语法loop
替换with_*
我们
loop
在 Ansible 2.5 中添加。它还不能完全替代with_<lookup>
,但我们建议在大多数用例中使用它。所以你最终会得到
loop: "{{ my.variable }}"
然后在 Jinja 中访问字典的属性是使用语法完成的
{% for key, value in dict.items() %}
来源:https
://jinja.palletsprojects.com/en/2.11.x/templates/#for 所以在你的情况下:{% for key, value in item.items() %}
总之,证明这一点的有效剧本将是:
- hosts: all
gather_facts: no
tasks:
- debug:
msg: |
{% for key, value in item.items() %}
{{key}}: {{value}}
{% endfor %}
loop: "{{ my.variable }}"
vars:
my:
variable:
- name: test
path: /etc/apt
cert: key.crt
这产生了结果:
PLAY [all] *******************************************************************************************************
TASK [debug] *****************************************************************************************************
ok: [localhost] => (item={'name': 'test', 'path': '/etc/apt', 'cert': 'key.crt'}) => {
"msg": " name: test\n path: /etc/apt\n cert: key.crt\n"
}
PLAY RECAP *******************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
现在你只需要在你的模板和循环中重用它,你应该得到你所期望的。
推荐阅读
- xamarin - 使用 Xamarin 的带有箭头的操作表
- node.js - AWS S3上传0 B文件-node.js
- spring-boot - `SpringApplicationBuilder` 是否可以用于连接`@SpringBootApplication` 和`@SpringBootTest` 之间的父/子关系?
- vb.net - Selenium VB.Net 2019 保存画布图像
- r - 对多个时间间隔求和,而不计算 lubridate 中的重叠时间
- php - 无法删除 xml 中的元素
- 64-bit - .Net 内存转储中的大量死线程
- python - 如何通过 pyqt5 按钮启动多个函数实例?
- javascript - Javascript 在具有最小和最大纬度和经度值的表中查找并返回网格值
- html - 我需要帮助使用 Jsoup 从网站显示 html