From fce9f4f67961b2bcb6da453f6a0a063e63288b03 Mon Sep 17 00:00:00 2001 From: Alexander Gubin Date: Mon, 2 Jan 2017 10:50:04 +0100 Subject: [PATCH] shuffle filter: added optional 'seed' parameter --- docsite/rst/playbooks_filters.rst | 4 ++++ lib/ansible/plugins/filter/core.py | 8 ++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docsite/rst/playbooks_filters.rst b/docsite/rst/playbooks_filters.rst index 36517d8a8b..33de53d744 100644 --- a/docsite/rst/playbooks_filters.rst +++ b/docsite/rst/playbooks_filters.rst @@ -185,6 +185,10 @@ To get a random list from an existing list:: {{ ['a','b','c']|shuffle }} => ['c','a','b'] {{ ['a','b','c']|shuffle }} => ['b','c','a'] +As of Ansible version 2.3, it's also possible to shuffle a list idempotent. All you need is a seed.:: + + {{ ['a','b','c']|shuffle(seed=inventory_hostname) }} => ['b','a','c'] + note that when used with a non 'listable' item it is a noop, otherwise it always returns a list diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 2666e2808c..70dfaacc06 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -217,10 +217,14 @@ def rand(environment, end, start=None, step=None, seed=None): else: raise errors.AnsibleFilterError('random can only be used on sequences and integers') -def randomize_list(mylist): +def randomize_list(mylist, seed=None): try: mylist = list(mylist) - shuffle(mylist) + if seed: + r = Random(seed) + r.shuffle(mylist) + else: + shuffle(mylist) except: pass return mylist