Debian Codegraph @

ansible_collections/community/general/plugins/lookup/flattened.py

raw
1 # Copyright (c) 2013, Serge van Ginderachter <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: flattened
9 author: Serge van Ginderachter (!UNKNOWN) <[email protected]>
10 short_description: Return single list completely flattened
11 description:
12 - Given one or more lists, this lookup flattens any list elements found recursively until only 1 list is left.
13 options:
14 _terms:
15 description: Lists to flatten.
16 type: list
17 elements: raw
18 required: true
19 notes:
20 - Unlike the P(ansible.builtin.items#lookup) lookup which only flattens 1 level, this plugin continues to flatten until
21 it cannot find lists anymore.
22 - Aka highlander plugin, there can only be one (list).
23 """
24
25 EXAMPLES = r"""
26 - name: "'unnest' all elements into single list"
27 ansible.builtin.debug:
28 msg: "all in one list {{lookup('community.general.flattened', [1,2,3,[5,6]], ['a','b','c'], [[5,6,1,3], [34,'a','b','c']])}}"
29 """
30
31 RETURN = r"""
32 _raw:
33 description:
34 - Flattened list.
35 type: list
36 """
37
38 from ansible.errors import AnsibleError
39 from ansible.plugins.lookup import LookupBase
40 from ansible.utils.listify import listify_lookup_plugin_terms
41
42 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
43
44
45 class LookupModule(LookupBase):
46 def _check_list_of_one_list(self, term):
47 # make sure term is not a list of one (list of one..) item
48 # return the final non list item if so
49
50 if isinstance(term, list) and len(term) == 1:
51 term = term[0]
52 if isinstance(term, list):
53 term = self._check_list_of_one_list(term)
54
55 return term
56
57 def _do_flatten(self, terms, variables):
58 ret = []
59 for term in terms:
60 term = self._check_list_of_one_list(term)
61
62 if term == "None" or term == "null":
63 # ignore undefined items
64 break
65
66 if isinstance(term, str):
67 # convert a variable to a list
68 term2 = listify_lookup_plugin_terms(term, templar=self._templar)
69 # but avoid converting a plain string to a list of one string
70 if term2 != [term]:
71 term = term2
72
73 if isinstance(term, list):
74 # if it is a list, check recursively for items that are a list
75 term = self._do_flatten(term, variables)
76 ret.extend(term)
77 else:
78 ret.append(term)
79
80 return ret
81
82 def run(self, terms, variables=None, **kwargs):
83 if not isinstance(terms, list):
84 raise AnsibleError("with_flattened expects a list")
85
86 self.set_options(var_options=variables, direct=kwargs)
87 check_for_wrong_terms(self, direct=kwargs)
88
89 return self._do_flatten(terms, variables)