Skip to content

Commit

Permalink
host - improve validation and conversion of MAC addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
evgeni committed Jul 26, 2024
1 parent 756ac2b commit 0499aad
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
2 changes: 2 additions & 0 deletions changelogs/fragments/host-validate_mac.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- host - improve validation and conversion of MAC addresses
31 changes: 24 additions & 7 deletions plugins/modules/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@
mac:
description:
- MAC address of the primary interface of the host.
- Please include leading zeros and separate nibbles by colons, otherwise the execution will not be idempotent.
- Example EE:BB:01:02:03:04
type: str
type: mac
required: false
comment:
description:
Expand Down Expand Up @@ -383,6 +381,8 @@
ForemanEntityAnsibleModule,
HostMixin,
)
from ansible.module_utils.basic import check_type_str
import re


def ensure_host_interfaces(module, entity, interfaces):
Expand Down Expand Up @@ -433,6 +433,26 @@ class ForemanHostModule(HostMixin, ForemanEntityAnsibleModule):
pass


MAC_REGEXP = r'([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}'
MAC_REGEXP_64BIT = r'([a-f0-9]{1,2}:){19}[a-f0-9]{1,2}'


def mac(value):
final_value = check_type_str(value)
if ':' in final_value:
split_by = ':'
elif '-' in final_value:
split_by = '-'
else:
raise TypeError("'{0}' is not a valid MAC address".format(value))
mac_parts = final_value.split(split_by)
final_value = ':'.join([part.zfill(2) for part in mac_parts])
final_value = final_value.lower()
if (len(final_value) == 17 and re.match(MAC_REGEXP, final_value, re.IGNORECASE)) or (len(final_value) == 59 and re.match(MAC_REGEXP_64BIT, final_value)):
return final_value
raise TypeError("'{0}' is not a valid MAC address".format(value))


def main():
module = ForemanHostModule(
foreman_spec=dict(
Expand All @@ -444,7 +464,7 @@ def main():
managed=dict(type='bool'),
build=dict(type='bool'),
ip=dict(),
mac=dict(),
mac=dict(type=mac),
comment=dict(),
owner=dict(type='entity', resource_type='users', flat_name='owner_id'),
owner_group=dict(type='entity', resource_type='usergroups', flat_name='owner_id'),
Expand Down Expand Up @@ -476,9 +496,6 @@ def main():
# When 'build' is not given and 'managed'=False, have to clear 'build' context that might exist on the server.
module.foreman_params['build'] = False

if 'mac' in module.foreman_params:
module.foreman_params['mac'] = module.foreman_params['mac'].lower()

if 'owner' in module.foreman_params:
module.foreman_params['owner_type'] = 'User'
elif 'owner_group' in module.foreman_params:
Expand Down

0 comments on commit 0499aad

Please sign in to comment.