From 3534bdf953bd0ab98c521b0f5e6ea5523d3f9ea8 Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Sun, 5 Oct 2014 20:53:06 -0400 Subject: [PATCH] added new 'shuffle' filter --- docsite/rst/playbooks_variables.rst | 13 +++++++++++++ lib/ansible/runner/filter_plugins/core.py | 8 ++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docsite/rst/playbooks_variables.rst b/docsite/rst/playbooks_variables.rst index 86146cdd0f0..ba852102931 100644 --- a/docsite/rst/playbooks_variables.rst +++ b/docsite/rst/playbooks_variables.rst @@ -297,6 +297,19 @@ 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'] + + .. _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 61b80bce2c5..71cfd267dc4 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -28,7 +28,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 +from random import SystemRandom, shuffle from jinja2.filters import environmentfilter @@ -235,6 +235,9 @@ 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): + shuffle(mylist) + return mylist class FilterModule(object): ''' Ansible core jinja2 filters ''' @@ -305,6 +308,7 @@ class FilterModule(object): # version comparison 'version_compare': version_compare, - # random numbers + # random stuff 'random': rand, + 'shuffle': randomize_list, }