Add seed parameter to random_mac filter (#51841)

This commit is contained in:
s-hamann 2019-05-16 17:41:08 +00:00 committed by Nathaniel Case
parent a910d19533
commit 730456b402
3 changed files with 17 additions and 3 deletions

View file

@ -378,6 +378,10 @@ To get a random MAC address from a string prefix starting with '52:54:00'::
Note that if anything is wrong with the prefix string, the filter will issue an error.
As of Ansible version 2.9, it's also possible to initialize the random number generator from a seed. This way, you can create random-but-idempotent MAC addresses::
"{{ '52:54:00' | random_mac(seed=inventory_hostname) }}"
.. _random_filter:
Random Number Filter

View file

@ -36,7 +36,7 @@ import yaml
import datetime
from functools import partial
from random import Random, SystemRandom, shuffle, randint
from random import Random, SystemRandom, shuffle
from jinja2.filters import environmentfilter, do_groupby as _do_groupby
@ -533,7 +533,7 @@ def list_of_dict_key_value_elements_to_dict(mylist, key_name='key', value_name='
return dict((item[key_name], item[value_name]) for item in mylist)
def random_mac(value):
def random_mac(value, seed=None):
''' takes string prefix, and return it completed with random bytes
to get a complete 6 bytes MAC address '''
@ -558,8 +558,12 @@ def random_mac(value):
if len(err):
raise AnsibleFilterError('Invalid value (%s) for random_mac: %s' % (value, err))
if seed is None:
r = SystemRandom()
else:
r = Random(seed)
# Generate random int between x1000000000 and xFFFFFFFFFF
v = randint(68719476736, 1099511627775)
v = r.randint(68719476736, 1099511627775)
# Select first n chars to complement input prefix
remain = 2 * (6 - len(mac_items))
rnd = ('%x' % v)[:remain]

View file

@ -242,6 +242,12 @@
- "'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: Verify random_mac filter with seed
assert:
that:
- "'00:00:00' | random_mac(seed='test') == '00:00:00' | random_mac(seed='test')"
- "'00:00:00' | random_mac(seed='test') != '00:00:00' | random_mac(seed='another_test')"
- name: Verify that union can be chained
vars:
unions: '{{ [1,2,3]|union([4,5])|union([6,7]) }}'