From dcb3e349d2b9a5a1b1a32fecccf30bf14ef646f1 Mon Sep 17 00:00:00 2001 From: NilashishC Date: Mon, 27 Nov 2023 15:26:02 +0530 Subject: [PATCH] [AnsibleArgSpecValidator] remove empty keys from task args before validating Signed-off-by: NilashishC --- changelogs/fragments/validate.yaml | 3 ++ .../module_utils/common/argspec_validate.py | 7 +++-- plugins/module_utils/common/utils.py | 29 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 changelogs/fragments/validate.yaml diff --git a/changelogs/fragments/validate.yaml b/changelogs/fragments/validate.yaml new file mode 100644 index 00000000..14033927 --- /dev/null +++ b/changelogs/fragments/validate.yaml @@ -0,0 +1,3 @@ +--- +bugfixes: + - "AnsibleArgSpecValidator - removes empty keys in task args before validating against schema." diff --git a/plugins/module_utils/common/argspec_validate.py b/plugins/module_utils/common/argspec_validate.py index 18aad12e..0fa155d0 100644 --- a/plugins/module_utils/common/argspec_validate.py +++ b/plugins/module_utils/common/argspec_validate.py @@ -29,7 +29,10 @@ def _check_argspec(self): from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems -from ansible_collections.ansible.utils.plugins.module_utils.common.utils import dict_merge +from ansible_collections.ansible.utils.plugins.module_utils.common.utils import ( + dict_merge, + remove_empties, +) try: @@ -220,7 +223,7 @@ def _validate(self): ) updated_data = {} else: - mm = MonkeyModule(data=self._data, schema=self._schema, name=self._name) + mm = MonkeyModule(data=remove_empties(self._data), schema=self._schema, name=self._name) valid, errors, updated_data = mm.validate() return valid, errors, updated_data diff --git a/plugins/module_utils/common/utils.py b/plugins/module_utils/common/utils.py index 4ad63566..fb185227 100644 --- a/plugins/module_utils/common/utils.py +++ b/plugins/module_utils/common/utils.py @@ -109,3 +109,32 @@ def to_list(val): return [val] else: return list() + + +def remove_empties(cfg_dict): + """ + Generate final config dictionary + + :param cfg_dict: A dictionary parsed in the facts system + :rtype: A dictionary + :returns: A dictionary by eliminating keys that have null values + """ + final_cfg = {} + if not cfg_dict: + return final_cfg + + for key, val in iteritems(cfg_dict): + dct = None + if isinstance(val, dict): + child_val = remove_empties(val) + if child_val: + dct = {key: child_val} + elif isinstance(val, list) and val and all(isinstance(x, dict) for x in val): + child_val = [remove_empties(x) for x in val] + if child_val: + dct = {key: child_val} + elif val not in [None, [], {}, (), ""]: + dct = {key: val} + if dct: + final_cfg.update(dct) + return final_cfg