Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active November 8, 2023 16:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halberom/f9c519962f163e26568d to your computer and use it in GitHub Desktop.
Save halberom/f9c519962f163e26568d to your computer and use it in GitHub Desktop.
ansible - example of merging lists of dicts
# ansible_plugins/filter_plugins/extras.py
def merge_dicts(value, dict1):
# return a merged dict
result = {}
result = value
result.update(dict1)
return result
def merge_lists_of_dicts(list1, list2):
# return a merged list
result = []
if len(list1) == len(list2):
for index,val in enumerate(list1):
merged_items = merge_dicts(list1[index], list2[index])
result.append(merged_items)
return result
class FilterModule(object):
''' Ansible extra jinja2 filters '''
def filters(self):
return {
'merge_dicts': merge_dicts,
'merge_lists_of_dicts': merge_lists_of_dicts,
}
PLAY: ***************************************************************************
TASK [set_fact foobar=[{u'type': u'cat', u'name': u'bob', u'activity': u'catnip'}, {u'type': u'dog', u'name': u'grace', u'activity': u'fetch'}, {u'type': u'moose', u'name': u'tim', u'activity': u'bowling'}]] ***
ok: [centos66]
TASK [debug var=foobar] *********************************************************
ok: [centos66] => {
"changed": false,
"foobar": [
{
"activity": "catnip",
"name": "bob",
"type": "cat"
},
{
"activity": "fetch",
"name": "grace",
"type": "dog"
},
{
"activity": "bowling",
"name": "tim",
"type": "moose"
}
]
}
---
- hosts: centos66
vars:
pet_details_list:
- {"type": "cat", "name": "bob" }
- {"type": "dog", "name": "grace"}
- {"type": "moose", "name": "tim" }
pet_activity_list:
- {"activity": "catnip", "name" "bob" }
- {"activity": "fetch", "name" "grace"}
- {"activity": "bowling", "name" "tim" }
tasks:
- set_fact:
foobar: "{{ pet_details_list | merge_lists_of_dicts(pet_activity_list) }}"
- debug:
var: foobar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment