Fix items2dict errors for incorrect list item type and missing keys (#77946)

* Fix items2dict errors for incorrect list item type and missing keys

* keep dict comprehension
pull/77967/head
Sloane Hertel 3 years ago committed by GitHub
parent 89e4fb71e6
commit f270b4e224
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,2 @@
bugfixes:
- items2dict - Handle error if an item is not a dictionary or is missing the required keys (https://github.com/ansible/ansible/issues/70337).

@ -543,7 +543,15 @@ def list_of_dict_key_value_elements_to_dict(mylist, key_name='key', value_name='
if not is_sequence(mylist):
raise AnsibleFilterTypeError("items2dict requires a list, got %s instead." % type(mylist))
return dict((item[key_name], item[value_name]) for item in mylist)
try:
return dict((item[key_name], item[value_name]) for item in mylist)
except KeyError:
raise AnsibleFilterTypeError(
"items2dict requires each dictionary in the list to contain the keys '%s' and '%s', got %s instead."
% (key_name, value_name, mylist)
)
except TypeError:
raise AnsibleFilterTypeError("items2dict requires a list of dictionaries, got %s instead." % mylist)
def path_join(paths):

@ -599,7 +599,7 @@
- dict2items_fail is failed
- '"dict2items requires a dictionary" in dict2items_fail.msg'
- name: Verify items2dict throws on non-Mapping
- name: Verify items2dict throws on non-list
set_fact:
foo: '{{True|items2dict}}'
ignore_errors: yes
@ -612,6 +612,50 @@
- items2dict_fail is failed
- '"items2dict requires a list" in items2dict_fail.msg'
- name: Verify items2dict throws on list of non-Mapping
set_fact:
foo: '{{[True]|items2dict}}'
ignore_errors: yes
register: items2dict_fail
- name: Verify items2dict
assert:
that:
- items2dict_fail is failed
- '"items2dict requires a list of dictionaries" in items2dict_fail.msg'
- name: Verify items2dict throws on missing key
set_fact:
foo: '{{ list_of_dicts | items2dict}}'
vars:
list_of_dicts: [{"key": "foo", "value": "bar"}, {"notkey": "banana", "value": "fruit"}]
ignore_errors: yes
register: items2dict_fail
- name: Verify items2dict
assert:
that:
- items2dict_fail is failed
- error in items2dict_fail.msg
vars:
error: "items2dict requires each dictionary in the list to contain the keys 'key' and 'value'"
- name: Verify items2dict throws on missing value
set_fact:
foo: '{{ list_of_dicts | items2dict}}'
vars:
list_of_dicts: [{"key": "foo", "value": "bar"}, {"key": "banana", "notvalue": "fruit"}]
ignore_errors: yes
register: items2dict_fail
- name: Verify items2dict
assert:
that:
- items2dict_fail is failed
- error in items2dict_fail.msg
vars:
error: "items2dict requires each dictionary in the list to contain the keys 'key' and 'value'"
- name: Verify path_join throws on non-string and non-sequence
set_fact:
foo: '{{True|path_join}}'

Loading…
Cancel
Save