From a6068b09accdd0acd76fafe8c635a28d505305da Mon Sep 17 00:00:00 2001 From: James Cammarata Date: Tue, 22 Apr 2014 14:21:00 -0500 Subject: [PATCH] Fix collision in random filter name by merging functionality Merges the functionality of the original jinja2 random filter with the one we provide. Fixes #7113 --- docsite/rst/playbooks_variables.rst | 7 +++++++ lib/ansible/runner/filter_plugins/core.py | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docsite/rst/playbooks_variables.rst b/docsite/rst/playbooks_variables.rst index ce70daf54ff..23c845c7549 100644 --- a/docsite/rst/playbooks_variables.rst +++ b/docsite/rst/playbooks_variables.rst @@ -241,6 +241,13 @@ Random Number Filter .. versionadded:: 1.6 +This filter can be used similar to the default jinja2 random filter (returning a random item from a sequence of +items), but can also generate a random number based on a range. + +To get a random item from a list:: + + {{ ['a','b','c']|random }} => 'c' + To get a random number from 0 to supplied end:: {{ 59 |random}} * * * * root /script/from/cron diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index 8557a42c072..293ebc4ae36 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -181,9 +181,20 @@ def version_compare(value, version, operator='eq', strict=False): except Exception, e: raise errors.AnsibleFilterError('Version comparison: %s' % e) -def rand(end, start=0, step=1): +def rand(end, start=None, step=None): r = SystemRandom() - return r.randrange(start, end, step) + if isinstance(end, (int, long)): + if not start: + start = 0 + if not step: + step = 1 + return r.randrange(start, end, step) + elif hasattr(end, '__iter__'): + if start or step: + raise errors.AnsibleFilterError('start and step can only be used with integer values') + return r.choice(end) + else: + raise errors.AnsibleFilterError('random can only be used on sequences and integers') class FilterModule(object): ''' Ansible core jinja2 filters '''