filter - 在循环中使用 ansible jinja2 组合过滤器
问题描述
我得到了这个简单的剧本,我试图使用combine
过滤器从键/值对列表中构造一个字典。问题是在循环对时它似乎不起作用(我试过循环,with_dict,with_items)。
- name: test jinja2 combine filter
hosts: localhost
- name: test combine
vars:
x: {'three', 3}
set_fact:
x: "{{ x | combine(item) }}"
with_items: [{'one': 1},{'two': 2}]
# I am expecting to see the two new dicts here,
# but only the last one in the list is added
- name: print x
debug: msg={{ x }}
预期输出:
ok: [localhost] => {
"msg": {
"three": 3,
"one": 1,
"two": 2
}
}
我的结果:
ok: [localhost] => {
"msg": {
"three": 3,
"two": 2
}
}
从这篇文章来看,似乎没有针对此类问题的开箱即用解决方案。虽然编写自定义插件并不难,但我仍然想知道是否有不编写插件的标准解决方案。
解决方案
希望您已经找到了可行的解决方案...如果没有,这可以帮助您:
- name: test jinja2 combine filter
hosts: localhost
vars:
x:
three: 3
xx:
one: 1
two: 2
tasks:
- debug:
var: x
- debug:
var: xx
- name: test combine
set_fact:
z: "{{ x | combine(xx) | to_nice_json }}"
- debug:
var: z
这给了我:
PLAY [test jinja2 combine filter] ***************************
TASK [debug] ***************************
ok: [localhost] => {
"x": {
"three": 3
}
}
TASK [debug] ***************************
ok: [localhost] => {
"xx": {
"one": 1,
"two": 2
}
}
TASK [test combine] ***************************
ok: [localhost]
TASK [debug] ***************************
ok: [localhost] => {
"z": {
"one": 1,
"three": 3,
"two": 2
}
}
PLAY RECAP ***************************
localhost : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
推荐阅读
- sql - SQL Server 成功创建调用 NON-EXISTING 函数的存储过程
- c - 分配块的结构初始化导致分段错误
- android - 将 PDF 保存在 Android 11 上的外部下载目录中
- javascript - 如何在bingmap中获取比例尺
- javascript - 有没有更简单的递归方式来编写这个函数?
- python - python rss feed生成器给出错误的格式
- c++ - 我正在学习编程,我想知道是否有任何方法可以让这个代码只接受整数
- kotlin - Kotlin 提取字母并在字符串中仅保留数字
- javascript - 如何通过消除双重等待和 DRY 代码进行重构?
- node.js - NodeJS docker guide 无缘无故地为全局依赖使用非默认路径。为什么这是最佳实践?