From d3441bc313bfca1771d17c9af14b95626b073d0b Mon Sep 17 00:00:00 2001 From: Matt Martz Date: Tue, 9 Feb 2021 09:37:15 -0600 Subject: [PATCH] Add new split filter (#73532) * Add version added --- changelogs/fragments/split-filter.yml | 2 ++ docs/docsite/rst/user_guide/playbooks_filters.rst | 6 ++++++ lib/ansible/plugins/filter/core.py | 3 ++- test/integration/targets/filter_core/tasks/main.yml | 9 +++++++++ 4 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/split-filter.yml diff --git a/changelogs/fragments/split-filter.yml b/changelogs/fragments/split-filter.yml new file mode 100644 index 00000000000..c9d311207da --- /dev/null +++ b/changelogs/fragments/split-filter.yml @@ -0,0 +1,2 @@ +minor_changes: +- Filters - Add new ``split`` filter for splitting strings diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index d65b0a8f5d6..1f0c9c9de3f 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -1612,6 +1612,12 @@ To concatenate a list into a string:: {{ list | join(" ") }} +To split a sting into a list:: + +.. versionadded:: 2.11 + + {{ csv_string | split(",") }} + To work with Base64 encoded strings:: {{ encoded | b64decode }} diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 591d3e8386e..f277e095bb2 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -41,7 +41,7 @@ from random import Random, SystemRandom, shuffle from jinja2.filters import environmentfilter, do_groupby as _do_groupby from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleFilterTypeError -from ansible.module_utils.six import iteritems, string_types, integer_types, reraise +from ansible.module_utils.six import iteritems, string_types, integer_types, reraise, text_type from ansible.module_utils.six.moves import reduce, shlex_quote from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.module_utils.common.collections import is_sequence @@ -662,4 +662,5 @@ class FilterModule(object): 'dict2items': dict_to_list_of_dict_key_value_elements, 'items2dict': list_of_dict_key_value_elements_to_dict, 'subelements': subelements, + 'split': partial(unicode_wrap, text_type.split), } diff --git a/test/integration/targets/filter_core/tasks/main.yml b/test/integration/targets/filter_core/tasks/main.yml index 4a21f543d12..8ab9d44676b 100644 --- a/test/integration/targets/filter_core/tasks/main.yml +++ b/test/integration/targets/filter_core/tasks/main.yml @@ -608,3 +608,12 @@ - thing|quote == "''" vars: thing: null + +- name: split filter + assert: + that: + - splitty|map('split', ',')|flatten|map('int') == [1, 2, 3, 4, 5, 6] + vars: + splitty: + - "1,2,3" + - "4,5,6"