Debian Codegraph @

lib/ansible/plugins/lookup/__init__.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 from abc import abstractmethod
21
22 from ansible.errors import AnsibleFileNotFound
23 from ansible.plugins import AnsiblePlugin
24 from ansible.utils.display import Display
25
26 import typing as t
27
28 if t.TYPE_CHECKING:
29 from ansible.parsing import dataloader as _dataloader
30 from ansible import template as _template
31
32 display = Display()
33
34 __all__ = ['LookupBase']
35
36
37 class LookupBase(AnsiblePlugin):
38 accept_args_markers: t.ClassVar[bool] = False
39 """
40 When `False`, plugin invocation is skipped when a top-level argument is a `Marker`, with the first such value substituted as the plugin result.
41 This ensures that only plugins which understand `Marker` instances for top-level arguments will encounter them.
42 """
43
44 accept_lazy_markers: t.ClassVar[bool] = False
45 """
46 When `False`, plugins will trigger a `MarkerError` exception when attempting to retrieve a `Marker` from a lazy container.
47 This ensures that only plugins which understand lazy retrieval of `Marker` instances will encounter them.
48 """
49
50 def __init__(self, loader: _dataloader.DataLoader | None = None, templar: _template.Templar | None = None, **kwargs) -> None:
51
52 super(LookupBase, self).__init__()
53
54 self._loader = loader
55 self._templar = templar
56
57 # Backwards compat: self._display isn't really needed, just import the global display and use that.
58 self._display = display
59
60 def get_basedir(self, variables):
61 if 'role_path' in variables:
62 return variables['role_path']
63 else:
64 return self._loader.get_basedir()
65
66 @staticmethod
67 def _flatten(terms):
68 ret = []
69 for term in terms:
70 if isinstance(term, (list, tuple)):
71 ret.extend(term)
72 else:
73 ret.append(term)
74 return ret
75
76 @staticmethod
77 def _combine(a, b):
78 results = []
79 for x in a:
80 for y in b:
81 results.append(LookupBase._flatten([x, y]))
82 return results
83
84 @staticmethod
85 def _flatten_hash_to_list(terms):
86 ret = []
87 for key in terms:
88 ret.append({'key': key, 'value': terms[key]})
89 return ret
90
91 @abstractmethod
92 def run(self, terms, variables, **kwargs):
93 """
94 When the playbook specifies a lookup, this method is run. The
95 arguments to the lookup become the arguments to this method. One
96 additional keyword argument named ``variables`` is added to the method
97 call. It contains the variables available to ansible at the time the
98 lookup is templated. For instance::
99
100 "{{ lookup('url', 'https://toshio.fedorapeople.org/one.txt', validate_certs=True) }}"
101
102 would end up calling the lookup plugin named url's run method like this::
103 run(['https://toshio.fedorapeople.org/one.txt'], variables=available_variables, validate_certs=True)
104
105 Lookup plugins can be used within playbooks for looping. When this
106 happens, the first argument is a list containing the terms. Lookup
107 plugins can also be called from within playbooks to return their
108 values into a variable or parameter. If the user passes a string in
109 this case, it is converted into a list.
110
111 Errors encountered during execution should be returned by raising
112 AnsibleError() with a message describing the error.
113
114 Any strings returned by this method that could ever contain non-ascii
115 must be converted into python's unicode type as the strings will be run
116 through jinja2 which has this requirement. You can use::
117
118 from ansible.module_utils.common.text.converters import to_text
119 result_string = to_text(result_string)
120 """
121 pass
122
123 def find_file_in_search_path(self, myvars, subdir, needle, ignore_missing=False):
124 """
125 Return a file (needle) in the task's expected search path.
126 """
127
128 if 'ansible_search_path' in myvars:
129 paths = myvars['ansible_search_path']
130 else:
131 paths = [self.get_basedir(myvars)]
132
133 result = None
134 try:
135 result = self._loader.path_dwim_relative_stack(paths, subdir, needle, is_role=bool('role_path' in myvars))
136 except AnsibleFileNotFound:
137 if not ignore_missing:
138 self._display.warning("Unable to find '%s' in expected paths (use -vvvvv to see paths)" % needle)
139
140 return result
141
142 def _deprecate_inline_kv(self):
143 # TODO: place holder to deprecate in future version allowing for long transition period
144 # self._display.deprecated('Passing inline k=v values embedded in a string to this lookup. Use direct ,k=v, k2=v2 syntax instead.', version='2.18')
145 pass