Debian Codegraph @

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

raw
1 # Copyright (c) 2013, Bradley Young <[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 author: Unknown (!UNKNOWN)
9 name: cartesian
10 short_description: Returns the cartesian product of lists
11 description:
12 - Takes the input lists and returns a list that represents the product of the input lists.
13 - It is clearer with an example, it turns [1, 2, 3], [a, b] into [1, a], [1, b], [2, a], [2, b], [3, a], [3, b].
14 - You can see the exact syntax in the examples section.
15 options:
16 _terms:
17 description:
18 - A set of lists.
19 type: list
20 elements: list
21 required: true
22 """
23
24 EXAMPLES = r"""
25 - name: Example of the change in the description
26 ansible.builtin.debug:
27 msg: "{{ lookup('community.general.cartesian', [1,2,3], [a, b])}}"
28
29 - name: loops over the cartesian product of the supplied lists
30 ansible.builtin.debug:
31 msg: "{{item}}"
32 with_community.general.cartesian:
33 - "{{list1}}"
34 - "{{list2}}"
35 - [1, 2, 3, 4, 5, 6]
36 """
37
38 RETURN = r"""
39 _list:
40 description:
41 - List of lists composed of elements of the input lists.
42 type: list
43 elements: list
44 """
45
46 from itertools import product
47
48 from ansible.errors import AnsibleError
49 from ansible.plugins.lookup import LookupBase
50 from ansible.utils.listify import listify_lookup_plugin_terms
51
52 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
53
54
55 class LookupModule(LookupBase):
56 """
57 Create the cartesian product of lists
58 """
59
60 def _lookup_variables(self, terms):
61 """
62 Turn this:
63 terms == ["1,2,3", "a,b"]
64 into this:
65 terms == [[1,2,3], [a, b]]
66 """
67 results = []
68 for x in terms:
69 results.append(listify_lookup_plugin_terms(x, templar=self._templar))
70 return results
71
72 def run(self, terms, variables=None, **kwargs):
73 self.set_options(var_options=variables, direct=kwargs)
74 check_for_wrong_terms(self, direct=kwargs)
75
76 terms = self._lookup_variables(terms)
77
78 my_list = terms[:]
79 if len(my_list) == 0:
80 raise AnsibleError("with_cartesian requires at least one element in each list")
81
82 return [self._flatten(x) for x in product(*my_list)]