1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Merge pull request #9270 from bcoca/do_the_shuffle

added new 'shuffle' filter
This commit is contained in:
Brian Coca 2014-11-20 13:43:00 -05:00
commit 0edaa6f790
2 changed files with 24 additions and 2 deletions

View file

@ -297,6 +297,20 @@ Get a random number from 1 to 100 but in steps of 10::
{{ 100 |random(start=1, step=10) }} => 51
Shuffle Filter
--------------
.. versionadded:: 1.8
This filter will randomize an existing list, giving a differnt order every invocation.
To get a random list from an existing list::
{{ ['a','b','c']|shuffle }} => ['c','a','b']
{{ ['a','b','c']|shuffle }} => ['b','c','a']
note that when used with a non 'listable' item it is a noop, otherwise it always returns a list
.. _other_useful_filters:
Other Useful Filters

View file

@ -28,7 +28,7 @@ import operator as py_operator
from ansible import errors
from ansible.utils import md5s, checksum_s
from distutils.version import LooseVersion, StrictVersion
from random import SystemRandom
from random import SystemRandom, shuffle
from jinja2.filters import environmentfilter
@ -235,6 +235,13 @@ def rand(environment, end, start=None, step=None):
else:
raise errors.AnsibleFilterError('random can only be used on sequences and integers')
def randomize_list(mylist):
try:
mylist = list(mylist)
shuffle(mylist)
except:
pass
return mylist
class FilterModule(object):
''' Ansible core jinja2 filters '''
@ -310,6 +317,7 @@ class FilterModule(object):
# version comparison
'version_compare': version_compare,
# random numbers
# random stuff
'random': rand,
'shuffle': randomize_list,
}