Merge pull request #6917 from bcoca/random_filter_clean

simple random filter
This commit is contained in:
jctanner 2014-04-10 15:15:05 -04:00
commit bfb25f4f89
2 changed files with 29 additions and 0 deletions

View file

@ -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) }} {{ 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:
Other Useful Filters Other Useful Filters

View file

@ -27,6 +27,7 @@ import operator as py_operator
from ansible import errors from ansible import errors
from ansible.utils import md5s from ansible.utils import md5s
from distutils.version import LooseVersion, StrictVersion from distutils.version import LooseVersion, StrictVersion
from random import SystemRandom
def to_nice_yaml(*a, **kw): def to_nice_yaml(*a, **kw):
'''Make verbose, human readable yaml''' '''Make verbose, human readable yaml'''
@ -180,6 +181,10 @@ def version_compare(value, version, operator='eq', strict=False):
except Exception, e: except Exception, e:
raise errors.AnsibleFilterError('Version comparison: %s' % 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): class FilterModule(object):
''' Ansible core jinja2 filters ''' ''' Ansible core jinja2 filters '''
@ -245,5 +250,8 @@ class FilterModule(object):
# version comparison # version comparison
'version_compare': version_compare, 'version_compare': version_compare,
# random numbers
'random': rand,
} }