![](/img/trans.png)
[英]How do I filter a list by existance of an attribute in ansible/jinja2?
[英]Use ansible jinja2 combine filter in a loop
我得到了这个简单的剧本,我正在尝试使用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
}
}
从这篇文章来看,似乎没有针对此类问题的开箱即用的解决方案。 虽然编写自定义插件并不难,但我仍然想知道是否有不编写插件的标准解决方案。
试试这个ansible-playbook -c local <file.yaml
- hosts: localhost
tasks:
- 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 hashes here...
# but only the last one in the list is added
- name: print x
debug: msg={{ x }}
因此,坏消息是我无法使用 ansible 2.9 在本地复制您的体验(因此您可能正在经历他们认为是错误并已修复的行为),但我的假设是with_items:
行为正在重新执行vars:
语句作为循环的副作用,因此通过每个循环重置x
,相当于: with_items({vars, set_fact}, [{item},{item}])
而不是{vars, with_items(set_fact, ...)}
话虽如此,除非您的实际情况阻止它,否则您真正想要的不是迭代set_fact
而是在组合项上运行set_fact
:
- set_fact:
x: '{{ x | combine(*new_values) }}'
vars:
x: {"three": 3}
new_values: [{"one": 1}, {"two": 2}]
- debug: var=x
希望你已经找到了一个可行的解决方案......如果没有,这可以帮助你:
- 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.