Debian Codegraph @

lib/ansible/plugins/lookup/varnames.py

raw
1 # (c) 2017 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 DOCUMENTATION = """
6 name: varnames
7 author: Ansible Core Team
8 version_added: "2.8"
9 short_description: Lookup matching variable names
10 description:
11 - Retrieves a list of matching Ansible variable names.
12 positional: _terms
13 options:
14 _terms:
15 description: List of Python regex patterns to search for in variable names.
16 required: True
17 seealso:
18 - plugin_type: lookup
19 plugin: ansible.builtin.vars
20 """
21
22 EXAMPLES = """
23 - name: List variables that start with qz_
24 ansible.builtin.debug: msg="{{ lookup('ansible.builtin.varnames', '^qz_.+') }}"
25 vars:
26 qz_1: hello
27 qz_2: world
28 qa_1: "I won't show"
29 qz_: "I won't show either"
30
31 - name: Show all variables
32 ansible.builtin.debug: msg="{{ lookup('ansible.builtin.varnames', '.+') }}"
33
34 - name: Show variables with 'hosts' in their names
35 ansible.builtin.debug: msg="{{ q('varnames', 'hosts') }}"
36
37 - name: Find several related variables that end specific way
38 ansible.builtin.debug: msg="{{ query('ansible.builtin.varnames', '.+_zone$', '.+_location$') }}"
39
40 - name: display values from variables found via varnames (note "*" is used to dereference the list to a 'list of arguments')
41 debug: msg="{{ lookup('vars', *lookup('varnames', 'ansible_play_.+')) }}"
42
43 """
44
45 RETURN = """
46 _value:
47 description:
48 - List of the variable names requested.
49 type: list
50 """
51
52 import re
53
54 from ansible.errors import AnsibleError
55 from ansible.module_utils.common.text.converters import to_native
56 from ansible.plugins.lookup import LookupBase
57
58
59 class LookupModule(LookupBase):
60
61 def run(self, terms, variables=None, **kwargs):
62
63 if variables is None:
64 raise AnsibleError('No variables available to search')
65
66 self.set_options(var_options=variables, direct=kwargs)
67
68 ret = []
69 variable_names = list(variables.keys())
70 for term in terms:
71
72 if not isinstance(term, str):
73 raise AnsibleError('Invalid setting identifier, "%s" is not a string, it is a %s' % (term, type(term)))
74
75 try:
76 name = re.compile(term)
77 except Exception as e:
78 raise AnsibleError('Unable to use "%s" as a search parameter: %s' % (term, to_native(e)))
79
80 for varname in variable_names:
81 if name.search(varname):
82 ret.append(varname)
83
84 return ret