Skip to content

Commit

Permalink
ansible_freeipa_module: Ensure data type when retrieving parameter
Browse files Browse the repository at this point in the history
Some parameters, in modules, have a specific data type, but allow the
use of an empty string to clear the parameter.

By providing a method to retrieve the parameter with the correct data
type, or optionally an empty string, allows for consistency of parameter
handling between different modules.
  • Loading branch information
rjeffman committed Sep 18, 2023
1 parent e5b2c12 commit 0c48442
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions plugins/module_utils/ansible_freeipa_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,31 @@ def module_params_get_lowercase(module, name, allow_empty_string=False):
return value


def module_params_get_type(
module, name, datatype, fail_if_empty=False, allow_empty_string=False
):
value = module_params_get(module, name, allow_empty_string)
if fail_if_empty and value == "":
module.fail_json(
msg="Argument '%s' must not be an empty string" % (name,)
)
if value is not None and value != "":
try:
if datatype is bool:
# We let Ansible handle bool values
value = boolean(value)
else:
value = datatype(value)
except ValueError:
module.fail_json(
msg="Invalid value '%s' for argument '%s'" % (value, name)
)
except TypeError as terr:
# If Ansible fails to parse a boolean, it will raise TypeError
module.fail_json(msg="Param '%s': %s" % (name, str(terr)))
return value


def api_get_domain():
return api.env.domain

Expand Down Expand Up @@ -1072,6 +1097,27 @@ def params_get_lowercase(self, name, allow_empty_string=False):
"""
return module_params_get_lowercase(self, name, allow_empty_string)

def params_get_type(
self, name, datatype, fail_if_empty=False, allow_empty_string=False
):
"""
Retrieve value set for module parameter as a specific data type.
Parameters
----------
name: string
The name of the parameter to retrieve.
datatype: type
The type to convert the value to, if not empty.
fail_if_empty: bool
Fails if `value == ""`.
allow_empty_string: bool
The parameter allowes to have empty strings in a list
"""
return module_params_get_type(
self, name, datatype, fail_if_empty, allow_empty_string)

def params_fail_used_invalid(self, invalid_params, state, action=None):
"""
Fail module execution if one of the invalid parameters is not None.
Expand Down

0 comments on commit 0c48442

Please sign in to comment.