Skip to content

Commit 0b17715

Browse files
committed
dcnm_vrf: to_bool() fix to return correct value, or call fail_json()
The initial implementation would return True for e.g. "false" since bool(non-null-string) is always True. 1. Modify to explicitly compare against known boolean-like strings i.e. "false", "False", "true", and "True". 2. Add the caller to the error message for better debugging ability in the future.
1 parent 40d93d6 commit 0b17715

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

plugins/modules/dcnm_vrf.py

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -697,16 +697,35 @@ def __init__(self, module):
697697
self.failed_to_rollback = False
698698
self.WAIT_TIME_FOR_DELETE_LOOP = 5 # in seconds
699699

700-
@staticmethod
701-
def to_bool(key, dict_with_key):
700+
def to_bool(self, key, dict_with_key):
701+
"""
702+
# Summary
703+
704+
Given a dictionary and key, access dictionary[key] and
705+
try to convert the value therein to a boolean.
706+
707+
- If the value is a boolean, return a like boolean.
708+
- If the value is a boolean-like string (e.g. "false"
709+
"True", etc), return the value converted to boolean.
710+
711+
## Raises
712+
713+
- Call fail_json() if the value is not convertable to boolean.
714+
"""
702715
value = dict_with_key.get(key)
703-
try:
704-
# TODO: Any string value e.g. "false" will return True here.
705-
# We need to test for common bool-like strings e.g.:
706-
#if value in ["false", False] return False
707-
return bool(value)
708-
except:
709-
return value
716+
if value in ["false", "False", False]:
717+
return False
718+
if value in ["true", "True", True]:
719+
return True
720+
721+
method_name = inspect.stack()[0][3]
722+
caller = inspect.stack()[1][3]
723+
724+
msg = f"{self.class_name}.{method_name}: "
725+
msg += f"caller: {caller}: "
726+
msg = f"{str(value)} with type {type(value)} "
727+
msg += "is not convertable to boolean"
728+
self.module.fail_json(msg=msg)
710729

711730
def diff_for_attach_deploy(self, want_a, have_a, replace=False):
712731

0 commit comments

Comments
 (0)