diff --git a/docsite/rst/playbooks_variables.rst b/docsite/rst/playbooks_variables.rst index 18aa31dcf3..92f77fa170 100644 --- a/docsite/rst/playbooks_variables.rst +++ b/docsite/rst/playbooks_variables.rst @@ -234,6 +234,27 @@ be used. The default is ``False``, and if set as ``True`` will use more strict {{ sample_version_var | version_compare('1.0', operator='lt', strict=True) }} +.. _random_filter + +Random Number Filter +-------------------------- + +.. versionadded:: 1.6 + +To get a random number from 0 to supplied end:: + + {{ 59 |random}} * * * * root /script/from/cron + +Get a random number from 0 to 100 but in steps of 10:: + + {{ 100 |random(step=10) }} => 70 + +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 + + .. _other_useful_filters: Other Useful Filters diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index 8bad776cbe..8557a42c07 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -27,6 +27,7 @@ import operator as py_operator from ansible import errors from ansible.utils import md5s from distutils.version import LooseVersion, StrictVersion +from random import SystemRandom def to_nice_yaml(*a, **kw): '''Make verbose, human readable yaml''' @@ -180,6 +181,10 @@ 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): + r = SystemRandom() + return r.randrange(start, end, step) + class FilterModule(object): ''' Ansible core jinja2 filters ''' @@ -245,5 +250,8 @@ class FilterModule(object): # version comparison 'version_compare': version_compare, + + # random numbers + 'random': rand, }