json output1:
{
"VMID": "7283949-4658-3i93899-2bb1-36748",
"VMName": "terra01-dc-domain"
},
{
"VMID": "833bjhds949-42658-3idbj46-2bb1-33bsj",
"VMName": "terra02-dc-domain"
}
json output2:
{
"GroupName": "default.DC2-external-msw",
"GRP_Members": [
7283949-4658-3i93899-2bb1-36748
]
},
{
"GroupName": "default.DC2-external-msw-svr2016-dns",
"GRP_Members": [
833bjhds949-42658-3idbj46-2bb1-33bsj
]
},
通过"VMID"在output1中搜索output2,并将其替换为output2。
输出要求:
{
"GroupName": "default.DC2-external-msw",
"GRP_Members": [
terra01-dc-domain
]
},
{
"GroupName": "default.DC2-external-msw-svr2016-dns",
"GRP_Members": [
terra01-dc-domain
]
},
请告知,提前感谢
给定数据
output1:
- VMID: 7283949-4658-3i93899-2bb1-36748
VMName: terra01-dc-domain
- VMID: 833bjhds949-42658-3idbj46-2bb1-33bsj
VMName: terra02-dc-domain
output2:
- GroupName: default.DC2-external-msw
GRP_Members:
- 7283949-4658-3i93899-2bb1-36748
- GroupName: default.DC2-external-msw-svr2016-dns
GRP_Members:
- 833bjhds949-42658-3idbj46-2bb1-33bsj
从output1
创建字典output1_dict: "{{ output1|items2dict(key_name='VMID', value_name='VMName') }}"
为
output1_dict:
7283949-4658-3i93899-2bb1-36748: terra01-dc-domain
833bjhds949-42658-3idbj46-2bb1-33bsj: terra02-dc-domain
然后迭代output2并将列表中的VMID替换为VMName
- set_fact:
output: "{{ output|d([]) + [_item] }}"
loop: "{{ output2 }}"
vars:
_members: "{{ item.GRP_Members|map('extract', output1_dict)|list }}"
_item: "{{ item|combine({'GRP_Members': _members}) }}"
为
output:
- GRP_Members:
- terra01-dc-domain
GroupName: default.DC2-external-msw
- GRP_Members:
- terra02-dc-domain
GroupName: default.DC2-external-msw-svr2016-dns
完整剧本示例
- hosts: localhost
vars:
output1:
- VMID: 7283949-4658-3i93899-2bb1-36748
VMName: terra01-dc-domain
- VMID: 833bjhds949-42658-3idbj46-2bb1-33bsj
VMName: terra02-dc-domain
output2:
- GroupName: default.DC2-external-msw
GRP_Members:
- 7283949-4658-3i93899-2bb1-36748
- GroupName: default.DC2-external-msw-svr2016-dns
GRP_Members:
- 833bjhds949-42658-3idbj46-2bb1-33bsj
output1_dict: "{{ output1|items2dict(key_name='VMID', value_name='VMName') }}"
tasks:
- set_fact:
output: "{{ output|d([]) + [_item] }}"
loop: "{{ output2 }}"
vars:
_members: "{{ item.GRP_Members|map('extract', output1_dict)|list }}"
_item: "{{ item|combine({'GRP_Members': _members}) }}"
- debug:
var: output