Skip to content

Commit

Permalink
[AnsibleArgSpecValidator] remove empty keys from task args before val…
Browse files Browse the repository at this point in the history
…idating

Signed-off-by: NilashishC <[email protected]>
  • Loading branch information
NilashishC committed Nov 27, 2023
1 parent e0c809a commit dcb3e34
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
3 changes: 3 additions & 0 deletions changelogs/fragments/validate.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
bugfixes:
- "AnsibleArgSpecValidator - removes empty keys in task args before validating against schema."
7 changes: 5 additions & 2 deletions plugins/module_utils/common/argspec_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
29 changes: 29 additions & 0 deletions plugins/module_utils/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit dcb3e34

Please sign in to comment.