Debian Codegraph @

lib/ansible/plugins/lookup/indexed_items.py

raw
1 # (c) 2012, Michael DeHaan <[email protected]>
2 # (c) 2017 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: indexed_items
8 author: Michael DeHaan
9 version_added: "1.3"
10 short_description: rewrites lists to return 'indexed items'
11 description:
12 - use this lookup if you want to loop over an array and also get the numeric index of where you are in the array as you go
13 - any list given will be transformed with each resulting element having the it's previous position in item.0 and its value in item.1
14 positional: _terms
15 options:
16 _terms:
17 description: list of items
18 required: True
19 """
20
21 EXAMPLES = """
22 - name: indexed loop demo
23 ansible.builtin.debug:
24 msg: "at array position {{ item.0 }} there is a value {{ item.1 }}"
25 with_indexed_items:
26 - "{{ some_list }}"
27 """
28
29 RETURN = """
30 _raw:
31 description:
32 - list with each item.0 giving you the position and item.1 the value
33 type: list
34 elements: list
35 """
36
37 from ansible.plugins.lookup import LookupBase
38
39
40 class LookupModule(LookupBase):
41 def run(self, terms, variables=None, **kwargs):
42 items = self._flatten(terms)
43 return list(zip(range(len(items)), items))