如何通过某个键将两个字典与 ansible 结合起来
我有两个 yaml 字典,我需要按键连接它们,
server_groups:
- name: grp1
servers: server1-1,server1-2,server1-3
- name: grp2
servers: server2-1,server2-2,server2-3
- name: grp3
servers: server3-1,server3-2,server3-3
server_paths:
- name: path1
src: grp1
dest: grp2
payload: ...
- name: path2
src: grp3
dest: grp1
payload: ...
我想通过按组名称添加 src_servers 和 dest_servers 来丰富 server_paths 字典。
我尝试通过这种方式实现它:
- set_fact:
serverpaths: "{{ server_paths }}"
- set_fact:
serverpaths: "{{ serverpaths|combine({'dest_servers':server_groups| selectattr('name', 'equalto', item.dest) | map(attribute='servers') | first})}}"
loop: "{{ server_paths }}"
预期结果是:
server_paths:
- name: path1
src: server1-1,server1-2,server1-3
dest: server2-1,server2-2,server2-3
payload: ...
- name: path2
src: server3-1,server3-2,server3-3
dest: server1-1,server1-2,server1-3
payload: ...
它可以很好地连接,但仅返回最后一个丰富的元素。所以我很困惑如何获得所有丰富的元素?
I have two yaml dictionaries that i need to join between by key
server_groups:
- name: grp1
servers: server1-1,server1-2,server1-3
- name: grp2
servers: server2-1,server2-2,server2-3
- name: grp3
servers: server3-1,server3-2,server3-3
server_paths:
- name: path1
src: grp1
dest: grp2
payload: ...
- name: path2
src: grp3
dest: grp1
payload: ...
I want to enrich server_paths dictionary by adding src_servers and dest_servers by group name.
I tried to achieve it by such way:
- set_fact:
serverpaths: "{{ server_paths }}"
- set_fact:
serverpaths: "{{ serverpaths|combine({'dest_servers':server_groups| selectattr('name', 'equalto', item.dest) | map(attribute='servers') | first})}}"
loop: "{{ server_paths }}"
Expected result is:
server_paths:
- name: path1
src: server1-1,server1-2,server1-3
dest: server2-1,server2-2,server2-3
payload: ...
- name: path2
src: server3-1,server3-2,server3-3
dest: server1-1,server1-2,server1-3
payload: ...
It works fine with joining but returns only last enriched element. So I'm stuck how to get all enriched elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
的位置
将列表 server_groups 转换为字典 server_groups_dict,例如,将下面的表达式放入列表来源给出
现在您可以迭代列表 server_paths > 并创建所需的结构,例如
给出
注释
Convert the list server_groups to the dictionary server_groups_dict, e.g. put the expression below to the place where the lists come from
gives
Now you can iterate the list server_paths and create the required structure, e.g.
gives
Notes