Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added new 'shuffle' filter #9270

Merged
merged 4 commits into from
Nov 20, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions docsite/rst/playbooks_variables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo: 'differnt'


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
Expand Down
12 changes: 10 additions & 2 deletions lib/ansible/runner/filter_plugins/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from ansible import errors
from ansible.utils import md5s
from distutils.version import LooseVersion, StrictVersion
from random import SystemRandom
from random import SystemRandom, shuffle
from jinja2.filters import environmentfilter


Expand Down Expand Up @@ -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 '''
Expand Down Expand Up @@ -305,6 +312,7 @@ def filters(self):
# version comparison
'version_compare': version_compare,

# random numbers
# random stuff
'random': rand,
'shuffle': randomize_list,
}