Debian Codegraph @

lib/ansible/plugins/lookup/first_found.py

raw
1 # (c) 2013, seth vidal <[email protected]> red hat, inc
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: first_found
8 author: Seth Vidal (!UNKNOWN) <[email protected]>
9 version_added: historical
10 short_description: return first file found from list
11 description:
12 - This lookup checks a list of files and paths and returns the full path to the first combination found.
13 - As all lookups, when fed relative paths it will try use the current task's location first and go up the chain
14 to the containing locations of role / play / include and so on.
15 - The list of files has precedence over the paths searched.
16 For example, A task in a role has a 'file1' in the play's relative path, this will be used, 'file2' in role's relative path will not.
17 - Either a list of files O(_terms) or a key O(files) with a list of files is required for this plugin to operate.
18 notes:
19 - This lookup can be used in 'dual mode', either passing a list of file names or a dictionary that has O(files) and O(paths).
20 positional: _terms
21 options:
22 _terms:
23 description: A list of file names.
24 files:
25 description: A list of file names.
26 type: list
27 elements: string
28 default: []
29 paths:
30 description: A list of paths in which to look for the files.
31 type: list
32 elements: string
33 default: []
34 skip:
35 type: boolean
36 default: False
37 description:
38 - When V(True), return an empty list when no files are matched.
39 - This is useful when used with C(with_first_found), as an empty list return to C(with_) calls
40 causes the calling task to be skipped.
41 - When used as a template via C(lookup) or C(query), setting O(skip=True) will *not* cause the task to skip.
42 Tasks must handle the empty list return from the template.
43 - When V(False) and C(lookup) or C(query) specifies O(ignore:errors='ignore') all errors (including no file found,
44 but potentially others) return V(None) or an empty list respectively.
45 - When V(True) and C(lookup) or C(query) specifies O(ignore:errors='ignore'), no file found will return an empty
46 list and other potential errors return V(None) or empty list depending on the template call
47 (in other words return values of C(lookup) vs C(query)).
48 seealso:
49 - ref: playbook_task_paths
50 description: Search paths used for relative paths/files.
51 """
52
53
54 EXAMPLES = """
55 - name: Set _found_file to the first existing file, raising an error if a file is not found
56 ansible.builtin.set_fact:
57 _found_file: "{{ lookup('ansible.builtin.first_found', findme) }}"
58 vars:
59 findme:
60 - /path/to/foo.txt
61 - bar.txt # will be looked in files/ dir relative to role and/or play
62 - /path/to/biz.txt
63
64 - name: Set _found_file to the first existing file, or an empty list if no files found
65 ansible.builtin.set_fact:
66 _found_file: "{{ lookup('ansible.builtin.first_found', files, paths=['/extra/path'], skip=True) }}"
67 vars:
68 files:
69 - /path/to/foo.txt
70 - /path/to/bar.txt
71
72 - name: Include tasks only if one of the files exist, otherwise skip the task
73 ansible.builtin.include_tasks:
74 file: "{{ item }}"
75 with_first_found:
76 - files:
77 - path/tasks.yaml
78 - path/other_tasks.yaml
79 skip: True
80
81 - name: Include tasks only if one of the files exists, otherwise skip
82 ansible.builtin.include_tasks: '{{ tasks_file }}'
83 when: tasks_file is not none
84 vars:
85 tasks_file: "{{ lookup('ansible.builtin.first_found', files=['tasks.yaml', 'other_tasks.yaml'], errors='ignore') }}"
86
87 - name: |
88 copy first existing file found to /some/file,
89 looking in relative directories from where the task is defined and
90 including any play objects that contain it
91 ansible.builtin.copy:
92 src: "{{ lookup('ansible.builtin.first_found', findme) }}"
93 dest: /some/file
94 vars:
95 findme:
96 - foo
97 - "{{ inventory_hostname }}"
98 - bar
99
100 - name: same copy but specific paths
101 ansible.builtin.copy:
102 src: "{{ lookup('ansible.builtin.first_found', params) }}"
103 dest: /some/file
104 vars:
105 params:
106 files:
107 - foo
108 - "{{ inventory_hostname }}"
109 - bar
110 paths:
111 - /tmp/production
112 - /tmp/staging
113
114 - name: INTERFACES | Create Ansible header for /etc/network/interfaces
115 ansible.builtin.template:
116 src: "{{ lookup('ansible.builtin.first_found', findme)}}"
117 dest: "/etc/foo.conf"
118 vars:
119 findme:
120 - "{{ ansible_virtualization_type }}_foo.conf"
121 - "default_foo.conf"
122
123 - name: read vars from first file found, use 'vars/' relative subdir
124 ansible.builtin.include_vars: "{{lookup('ansible.builtin.first_found', params)}}"
125 vars:
126 params:
127 files:
128 - '{{ ansible_distribution }}.yml'
129 - '{{ ansible_os_family }}.yml'
130 - default.yml
131 paths:
132 - 'vars'
133 """
134
135 RETURN = """
136 _raw:
137 description:
138 - path to file found
139 type: list
140 elements: path
141 """
142
143 import collections.abc as c
144 import os
145 import re
146 import typing as t
147
148 from ansible._internal import _task
149 from ansible.errors import AnsibleError
150 from ansible.plugins.lookup import LookupBase
151 from ansible._internal._templating import _jinja_common
152 from ansible._internal._templating import _jinja_plugins
153 from ansible import template as _template
154 from ansible.utils.path import unfrackpath
155 from ansible.utils.display import Display
156 from ansible.module_utils.datatag import native_type_name
157
158
159 def _split_on(target: str, terms: str | list[str], splitters: str) -> list[str]:
160 termlist: list[str] = []
161
162 if isinstance(terms, str):
163 split_terms = re.split(r'[%s]' % ''.join(map(re.escape, splitters)), terms)
164
165 if split_terms == [terms]:
166 termlist = [terms]
167 else:
168 Display().deprecated(
169 msg=f'Automatic splitting of {target} on {splitters!r} is deprecated.',
170 help_text=f'Provide a list of paths for {target} instead.',
171 version='2.23',
172 obj=terms,
173 )
174
175 termlist = split_terms
176 else:
177 # added since options will already listify
178 for term in terms:
179 termlist.extend(_split_on(target, term, splitters))
180
181 return termlist
182
183
184 class LookupModule(LookupBase):
185 accept_args_markers = True # terms are allowed to be undefined
186 accept_lazy_markers = True # terms are allowed to be undefined
187
188 def _process_terms(self, terms: c.Sequence, variables: dict[str, t.Any]) -> list[str]:
189
190 total_search = []
191
192 # can use a dict instead of list item to pass inline config
193 for term in terms:
194 if isinstance(term, c.Mapping):
195 self.set_options(var_options=variables, direct=term)
196 files = self.get_option('files')
197 files_description = "the 'files' option"
198 elif isinstance(term, str):
199 files = [term]
200 files_description = "files"
201 elif isinstance(term, c.Sequence):
202 partial = self._process_terms(term, variables)
203 total_search.extend(partial)
204 continue
205 else:
206 raise AnsibleError(f"Invalid term supplied. A string, dict or list is required, not {native_type_name(term)!r}).")
207
208 paths = self.get_option('paths')
209
210 # magic extra splitting to create lists
211 filelist = _split_on(files_description, files, ',;')
212 pathlist = _split_on('the "paths" option', paths, ',:;')
213
214 # create search structure
215 if pathlist:
216 for path in pathlist:
217 for fn in filelist:
218 f = os.path.join(path, fn)
219 total_search.append(f)
220 else:
221 # NOTE: this is now 'extend', previously it would clobber all options, but we deemed that a bug
222 total_search.extend(filelist)
223
224 return total_search
225
226 def run(self, terms: list, variables=None, **kwargs):
227 if (first_marker := _template.get_first_marker_arg((), kwargs)) is not None:
228 first_marker.trip()
229
230 # if we're being invoked by TaskExecutor.get_loop_items(),
231 # recursively drop undefined values from terms for backwards compatibility
232 terms = _recurse_terms(terms, omit_undefined=_jinja_plugins._LookupContext.current().invoked_as_with)
233
234 try:
235 # invoked_as_with shouldn't be possible outside a TaskContext
236 te_action = _task.TaskContext.current().task.action # FIXME: this value has not been templated, it should be (historical problem)...
237 except ReferenceError:
238 te_action = 'file'
239
240 # based on the presence of `var`/`template`/`file` in the enclosing task action name, choose a subdir to search
241 for subdir in ['template', 'var', 'file']:
242 if subdir in te_action:
243 break
244
245 subdir += "s" # convert to the matching directory name
246 self.set_options(var_options=variables, direct=kwargs)
247
248 if not terms:
249 terms = self.get_option('files')
250
251 total_search = self._process_terms(terms, variables)
252
253 # NOTE: during refactor noticed that the 'using a dict' as term
254 # is designed to only work with 'one' otherwise inconsistencies will appear.
255 # see other notes below.
256
257 for fn in total_search:
258 # get subdir if set by task executor, default to files otherwise
259 path = self.find_file_in_search_path(variables, subdir, fn, ignore_missing=True)
260
261 # exit if we find one!
262 if path is not None:
263 return [unfrackpath(path, follow=False)]
264
265 skip = self.get_option('skip')
266
267 # if we get here, no file was found
268 if skip:
269 # NOTE: global skip won't matter, only last 'skip' value in dict term
270 return []
271
272 raise AnsibleError("No file was found when using first_found.")
273
274
275 def _recurse_terms(o: t.Any, omit_undefined: bool) -> t.Any:
276 """Recurse through supported container types, optionally omitting undefined markers and tripping all remaining markers, returning the result."""
277 match o:
278 case dict():
279 return {k: _recurse_terms(v, omit_undefined) for k, v in o.items() if not (omit_undefined and isinstance(v, _jinja_common.UndefinedMarker))}
280 case list():
281 return [_recurse_terms(v, omit_undefined) for v in o if not (omit_undefined and isinstance(v, _jinja_common.UndefinedMarker))]
282 case tuple():
283 return tuple(_recurse_terms(v, omit_undefined) for v in o if not (omit_undefined and isinstance(v, _jinja_common.UndefinedMarker)))
284 case _jinja_common.Marker():
285 o.trip()
286 case _:
287 return o