From 96ddd29c7ee79c42476989f2051f741564aca135 Mon Sep 17 00:00:00 2001 From: Brano Zarnovican Date: Sun, 13 Nov 2016 09:13:12 +0100 Subject: [PATCH] random filter: added optional 'seed' parameter implements #15621 --- docsite/rst/playbooks_filters.rst | 5 +++++ lib/ansible/plugins/filter/core.py | 9 ++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docsite/rst/playbooks_filters.rst b/docsite/rst/playbooks_filters.rst index 0e5769c50eb..a43cc087f9e 100644 --- a/docsite/rst/playbooks_filters.rst +++ b/docsite/rst/playbooks_filters.rst @@ -168,6 +168,11 @@ Get a random number from 1 to 100 but in steps of 10:: {{ 100 |random(1, 10) }} => 31 {{ 100 |random(start=1, step=10) }} => 51 +It's also possible to initialize random number generator from seed. This way, you can create random-but-idempotent +numbers (new in version 2.3):: + + {{ 59 |random(seed=inventory_hostname) }} * * * * root /script/from/cron + Shuffle Filter -------------- diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 39b92a28f86..804de360c95 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -31,7 +31,7 @@ import crypt import hashlib import string from functools import partial -from random import SystemRandom, shuffle +from random import Random, SystemRandom, shuffle from datetime import datetime import uuid @@ -199,8 +199,11 @@ def from_yaml(data): return data @environmentfilter -def rand(environment, end, start=None, step=None): - r = SystemRandom() +def rand(environment, end, start=None, step=None, seed=None): + if seed is None: + r = SystemRandom() + else: + r = Random(seed) if isinstance(end, (int, long)): if not start: start = 0