Debian Codegraph @

lib/ansible/plugins/lookup/together.py

raw
1 # (c) 2013, Bradley Young <[email protected]>
2 # (c) 2012-17 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 DOCUMENTATION = """
7 name: together
8 author: Bradley Young (!UNKNOWN) <[email protected]>
9 version_added: '1.3'
10 short_description: merges lists into synchronized list
11 description:
12 - Creates a list with the iterated elements of the supplied lists
13 - "To clarify with an example, [ 'a', 'b' ] and [ 1, 2 ] turn into [ ('a',1), ('b', 2) ]"
14 - This is basically the same as the 'zip_longest' filter and Python function
15 - Any 'unbalanced' elements will be substituted with 'None'
16 positional: _terms
17 options:
18 _terms:
19 description: list of lists to merge
20 required: True
21 """
22
23 EXAMPLES = """
24 - name: item.0 returns from the 'a' list, item.1 returns from the '1' list
25 ansible.builtin.debug:
26 msg: "{{ item.0 }} and {{ item.1 }}"
27 with_together:
28 - ['a', 'b', 'c', 'd']
29 - [1, 2, 3, 4]
30 """
31
32 RETURN = """
33 _list:
34 description: synchronized list
35 type: list
36 elements: list
37 """
38 import itertools
39
40 from ansible.errors import AnsibleError
41 from ansible.plugins.lookup import LookupBase
42
43
44 class LookupModule(LookupBase):
45 """
46 Transpose a list of arrays:
47 [1, 2, 3], [4, 5, 6] -> [1, 4], [2, 5], [3, 6]
48 Replace any empty spots in 2nd array with None:
49 [1, 2], [3] -> [1, 3], [2, None]
50 """
51 def run(self, terms, variables=None, **kwargs):
52 my_list = terms[:]
53 if len(my_list) == 0:
54 raise AnsibleError("with_together requires at least one element in each list")
55
56 return [self._flatten(x) for x in itertools.zip_longest(*my_list, fillvalue=None)]