How to compare two lists in ansible and print desired output below, i have looked other posts in stackoverflow regarding comparing/lookup list , but the way i want desired output is a bit different, unable to figure out the logic to get this working. Please point me to any post that can help me.Thanks
List1:
[
{
"DES": "server1",
"PORT": "E46",
},
{
"DESCRIP": "server2",
"PORT": "E47",
},
{
"DESCRIP": "server3",
"PORT": "E4",
},
{
"DESCRIP": "server4",
"PORT": "E7",
}
]
List2:
[
{
"INTERFACES": [
"E6",
"E8",
"E9",
"E10",
"E11",
"E12",
"E13",
"E14",
"E27",
"E28",
"E37",
"E43",
"E44",
"E45",
"E46",
"E47"
],
"VLAN_ID": "17"
},
{
"INTERFACES": [
"E7",
"E10",
"E11",
"E12",
"E13",
"E14",
"E27",
"E28",
"E45",
"E46"
],
"VLAN_ID": "16"
}
]
desired output:
If list1 PORT
value matches/present in list2 INTERFACES
then print something like this: server1 E46 has: VLAN_ID: 17 ; VLAN_ID: 16
or server2 E47 has: VLAN_ID: 17 ; NO VLAN_ID: 16
If list1 PORT
value dosen't matches/present in list2 INTERFACES
then print something like server3 E4 has NO VLAN_ID: 17 NO VLAN_ID: 16
below is full desired print:
server1 E46 has: VLAN_ID: 17 ; VLAN_ID: 16
server2 E47 has: VLAN_ID: 17 ; NO VLAN_ID: 16
server3 E4 has: NO VLAN_ID: 17 ; NO VLAN_ID: 16
server4 E7 has: VLAN_ID: 16 ; NO VLAN_ID: 17
CodePudding user response:
For example
- set_fact:
srv_id: "{{ srv_id|d({})|combine({item.DESCRIP: _id}) }}"
loop: "{{ List1 }}"
vars:
_id: "{{ List2|
selectattr('INTERFACES', 'contains', item.PORT)|
map(attribute='VLAN_ID')|
list }}"
gives
srv_id:
server1: ['17', '16']
server2: ['17']
server3: []
server4: ['16']
(Formatting should be trivial.)