diff --git a/changelogs/fragments/random_mac-random-int-fix.yaml b/changelogs/fragments/random_mac-random-int-fix.yaml new file mode 100644 index 0000000000..73ced9fa41 --- /dev/null +++ b/changelogs/fragments/random_mac-random-int-fix.yaml @@ -0,0 +1,2 @@ +bugfixes: + - random_mac - generate a proper MAC address when the provided vendor prefix is two or four characters (https://github.com/ansible/ansible/issues/50838) diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index f9314accdb..919cbe0aa9 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -37,7 +37,7 @@ import yaml from collections import Mapping, MutableMapping import datetime from functools import partial -from random import Random, SystemRandom, shuffle, random +from random import Random, SystemRandom, shuffle, randint from jinja2.filters import environmentfilter, do_groupby as _do_groupby @@ -543,8 +543,8 @@ def random_mac(value): if len(err): raise AnsibleFilterError('Invalid value (%s) for random_mac: %s' % (value, err)) - # Generate random float and make it int - v = int(random() * 10.0**10) + # Generate random int between x1000000000 and xFFFFFFFFFF + v = randint(68719476736, 1099511627775) # Select first n chars to complement input prefix remain = 2 * (6 - len(mac_items)) rnd = ('%x' % v)[:remain] diff --git a/test/integration/targets/filters/tasks/main.yml b/test/integration/targets/filters/tasks/main.yml index a80c6814aa..6d5352e9b2 100644 --- a/test/integration/targets/filters/tasks/main.yml +++ b/test/integration/targets/filters/tasks/main.yml @@ -235,7 +235,11 @@ - name: Verify random_mac filter assert: that: + - "'00' | random_mac is match('^00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')" + - "'00:00' | random_mac is match('^00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')" - "'00:00:00' | random_mac is match('^00:00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')" + - "'00:00:00:00' | random_mac is match('^00:00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')" + - "'00:00:00:00:00' | random_mac is match('^00:00:00:00:00:[a-f0-9][a-f0-9]$')" - "'00:00:00' | random_mac != '00:00:00' | random_mac" - name: Ensure dict2items works with hostvars