Skip to content

Commit

Permalink
refactor validate_port function
Browse files Browse the repository at this point in the history
  • Loading branch information
superstes committed Aug 27, 2024
1 parent 6c2373d commit d85f081
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions plugins/module_utils/helper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,21 +179,26 @@ def get_multiple_matching(
return matching


def validate_port(module: AnsibleModule, port: (int, str), error_func: Callable = None) -> bool:
def _valid_port(port: int) -> bool:
return 0 < port < 65536


def validate_port(module: AnsibleModule, port: (int, str), port_range: bool = False, error_func: Callable = None) -> bool:
if error_func is None:
error_func = module.fail_json

if port == 'any' or is_unset(port):
return True

try:
if '-' in str(port):
start_port, end_port = map(int, str(port).split('-'))
if (start_port < 1 or start_port > 65535) or (end_port < 1 or end_port > 65535) or (start_port > end_port):
if port_range and str(port).find(':') != -1:
start_port, end_port = map(int, str(port).split(':', 1))
if start_port > end_port or not _valid_port(start_port) or not _valid_port(end_port):
error_func(f"Value '{port}' is an invalid port range!")
return False

else:
if int(port) < 1 or int(port) > 65535:
if _valid_port(int(port)):
error_func(f"Value '{port}' is an invalid port!")
return False

Expand Down

0 comments on commit d85f081

Please sign in to comment.