Debian Codegraph @

lib/ansible/plugins/lookup/dict.py

raw
1 # (c) 2014, Kent R. Spillner <[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: dict
8 version_added: "1.5"
9 short_description: returns key/value pair items from dictionaries
10 description:
11 - Takes dictionaries as input and returns a list with each item in the list being a dictionary with 'key' and 'value' as
12 keys to the previous dictionary's structure.
13 positional: _terms
14 options:
15 _terms:
16 description:
17 - A list of dictionaries
18 required: True
19 """
20
21 EXAMPLES = """
22 vars:
23 users:
24 alice:
25 name: Alice Appleworth
26 telephone: 123-456-7890
27 bob:
28 name: Bob Bananarama
29 telephone: 987-654-3210
30 tasks:
31 # with predefined vars
32 - name: Print phone records
33 ansible.builtin.debug:
34 msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
35 loop: "{{ lookup('ansible.builtin.dict', users) }}"
36 # with inline dictionary
37 - name: show dictionary
38 ansible.builtin.debug:
39 msg: "{{item.key}}: {{item.value}}"
40 with_dict: {a: 1, b: 2, c: 3}
41 # Items from loop can be used in when: statements
42 - name: set_fact when alice in key
43 ansible.builtin.set_fact:
44 alice_exists: true
45 loop: "{{ lookup('ansible.builtin.dict', users) }}"
46 when: "'alice' in item.key"
47 """
48
49 RETURN = """
50 _list:
51 description:
52 - list of composed dictionaries with key and value
53 type: list
54 """
55
56 from collections.abc import Mapping
57
58 from ansible.errors import AnsibleError
59 from ansible.plugins.lookup import LookupBase
60
61
62 class LookupModule(LookupBase):
63
64 def run(self, terms, variables=None, **kwargs):
65 results = []
66 for term in terms:
67 # Expect any type of Mapping, notably hostvars
68 if not isinstance(term, Mapping):
69 raise AnsibleError(f"the 'dict' lookup plugin expects a dictionary, got '{term}' of type {type(term)})")
70
71 results.extend(self._flatten_hash_to_list(term))
72 return results