Ansible,将词典合并为一个
我有一个yaml文件示例(haproxy.yml): 我使用此剧本加载此文件:Ansible,将词典合并为一个,ansible,yaml,jinja2,Ansible,Yaml,Jinja2,我有一个yaml文件示例(haproxy.yml): 我使用此剧本加载此文件: --- - name: 'stack-example' hosts: localhost gather_facts: no tasks: - name: 'include' include_vars: file: 'haproxy.yml' - set_fact: try: '{{ try|default({}) | combine(item.
---
- name: 'stack-example'
hosts: localhost
gather_facts: no
tasks:
- name: 'include'
include_vars:
file: 'haproxy.yml'
- set_fact:
try: '{{ try|default({}) | combine(item.value) }}'
loop: '{{ lookup("dict", rules) }}'
- debug:
var: try
所有文件都是两个解释和重现我的问题:-)
我需要使用set\u fact
来处理我的变量
我的主要目标是将所有PHP**合并/分组到一个组中。
这是我需要的一个例子,我尝试了很多东西,包括组合映射查找但没有任何东西能给我预期的结果
我试着做到这一点:
{
"PHP53": [
{ "url": "php53-1-aa.my-example.com" },
{ "url": "php53-1-bb.my-example.com" },
{ "url": "php53-2-bb.my-example.com" },
{ "url": "php53-3-bb.my-example.com" }
],
"PHP55": [
{ "url": "php55-1-aa.my-example.com" },
{ "url": "php55-1-bb.my-example.com" },
{ "url": "php55-1-cc.my-example.com" }
],
"PHP56": [
{ "url": "php56-1-aa.my-example.com" },
{ "url": "php56-2-aa.my-example.com" },
{ "url": "php56-3-aa.my-example.com" },
{ "url": "php56-1-bb.my-example.com" },
{ "url": "php56-2-bb.my-example.com" },
{ "url": "php56-3-bb.my-example.com" },
{ "url": "php56-1-cc.my-example.com" },
{ "url": "php56-2-cc.my-example.com" },
{ "url": "php56-3-cc.my-example.com" },
],
"PHP72": [
{ "url": "php72-1-aa.my-example.com" },
{ "url": "php72-2-aa.my-example.com" },
{ "url": "php72-3-aa.my-example.com" },
{ "url": "php72-1-bb.my-example.com" },
{ "url": "php72-2-bb.my-example.com" },
{ "url": "php72-3-bb.my-example.com" }
]
}
如果有人有这样的想法?
非常感谢你的帮助
致以最诚挚的问候下面的任务就完成了
- set_fact:
rules_grouped: "{{ rules_grouped|
default({})|
combine({item.0: item.1|json_query('[].value')|flatten})
}}"
loop: "{{ rules|
dict2items|
json_query('[*].value')|
map('dict2items')|list|flatten|
groupby('key')
}}"
要了解循环如何工作,请将其放入调试并逐步添加过滤器
- debug
msg: "{{ rules|
dict2items
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')|
map('dict2items')|list|flatten
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')|
map('dict2items')|list|flatten|
groupby('key')
}}"
嗨,弗拉基米尔,感谢新时代对你的帮助:-)新时代你的解决方案正是我所期望的。我不知道它到底是如何运作的,但我会学习的。非常感谢。通过调试查看循环非常容易。我已经更新了答案。
- debug
msg: "{{ rules|
dict2items
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')|
map('dict2items')|list|flatten
}}"
- debug
msg: "{{ rules|
dict2items|
json_query('[*].value')|
map('dict2items')|list|flatten|
groupby('key')
}}"