diff --git a/.github/BOTMETA.yml b/.github/BOTMETA.yml index 5a5e62a19a..0aacb4b8de 100644 --- a/.github/BOTMETA.yml +++ b/.github/BOTMETA.yml @@ -53,6 +53,8 @@ files: $doc_fragments/xenserver.py: maintainers: bvitnik labels: xenserver + $filters/dict.py: + maintainers: felixfontein $filters/dict_kv.py: maintainers: giner $filters/jc.py: diff --git a/changelogs/fragments/dict-filter.yml b/changelogs/fragments/dict-filter.yml new file mode 100644 index 0000000000..1e9923e796 --- /dev/null +++ b/changelogs/fragments/dict-filter.yml @@ -0,0 +1,3 @@ +add plugin.filter: + - name: dict + description: "The ``dict`` function as a filter: converts a list of tuples to a dictionary" diff --git a/plugins/filter/dict.py b/plugins/filter/dict.py new file mode 100644 index 0000000000..3d20e752b1 --- /dev/null +++ b/plugins/filter/dict.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2021, Felix Fontein +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +def dict_filter(sequence): + '''Convert a list of tuples to a dictionary. + + Example: ``[[1, 2], ['a', 'b']] | community.general.dict`` results in ``{1: 2, 'a': 'b'}`` + ''' + return dict(sequence) + + +class FilterModule(object): + '''Ansible jinja2 filters''' + + def filters(self): + return { + 'dict': dict_filter, + } diff --git a/tests/integration/targets/filter_dict/aliases b/tests/integration/targets/filter_dict/aliases new file mode 100644 index 0000000000..3e81d77f98 --- /dev/null +++ b/tests/integration/targets/filter_dict/aliases @@ -0,0 +1,2 @@ +shippable/posix/group3 +skip/python2.6 # filters are controller only, and we no longer support Python 2.6 on the controller diff --git a/tests/integration/targets/filter_dict/tasks/main.yml b/tests/integration/targets/filter_dict/tasks/main.yml new file mode 100644 index 0000000000..ab88d3ff3f --- /dev/null +++ b/tests/integration/targets/filter_dict/tasks/main.yml @@ -0,0 +1,7 @@ +--- +- name: "Test dict filter" + assert: + that: + - "[['a', 'b']] | community.general.dict == dict([['a', 'b']])" + - "[['a', 'b'], [1, 2]] | community.general.dict == dict([['a', 'b'], [1, 2]])" + - "[] | community.general.dict == dict([])"