From c41632fad2ecc6f7306933666e5a73d9181a37fe Mon Sep 17 00:00:00 2001 From: Raymond Wanyoike Date: Mon, 17 Sep 2018 23:53:52 +0300 Subject: [PATCH] Add the key_name/value_name options to the dict2items filter (#45550) * Add the key_name/value_name options to dict2items - as with items2dict, allow users to configure the key/value name for dict2items, add "version added" and examples --- .../rst/user_guide/playbooks_filters.rst | 19 +++++++++++++++++++ lib/ansible/plugins/filter/core.py | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index 7eab897cc0d..37adc0f3e14 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -200,6 +200,25 @@ into:: - key: Environment value: dev +.. versionadded:: 2.8 + +``dict2items`` accepts 2 keyword arguments, ``key_name`` and ``value_name`` that allow configuration of the names of the keys to use for the transformation:: + + {{ files | dict2items(key_name='file', value_name='path') }} + +Which turns:: + + files: + users: /etc/passwd + groups: /etc/group + +into:: + + - file: users + path: /etc/passwd + - file: groups + path: /etc/group + items2dict filter ````````````````` diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 17309dd8aa5..26489864328 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -494,7 +494,7 @@ def subelements(obj, subelements, skip_missing=False): return results -def dict_to_list_of_dict_key_value_elements(mydict): +def dict_to_list_of_dict_key_value_elements(mydict, key_name='key', value_name='value'): ''' takes a dictionary and transforms it into a list of dictionaries, with each having a 'key' and 'value' keys that correspond to the keys and values of the original ''' @@ -503,7 +503,7 @@ def dict_to_list_of_dict_key_value_elements(mydict): ret = [] for key in mydict: - ret.append({'key': key, 'value': mydict[key]}) + ret.append({key_name: key, value_name: mydict[key]}) return ret