Debian Codegraph @

lib/ansible/parsing/dataloader.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 # Copyright: (c) 2017, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import copy
8 import os
9 import os.path
10 import pathlib
11 import re
12 import tempfile
13 import typing as t
14
15 from ansible import constants as C
16 from ansible.errors import AnsibleFileNotFound, AnsibleParserError
17 from ansible._internal._errors import _error_utils
18 from ansible.module_utils.basic import is_executable
19 from ansible._internal._datatag._tags import Origin, TrustedAsTemplate, SourceWasEncrypted
20 from ansible.module_utils._internal._datatag import AnsibleTagHelper
21 from ansible.module_utils.common.text.converters import to_bytes, to_text
22 from ansible.parsing.quoting import unquote
23 from ansible.parsing.utils.yaml import from_yaml
24 from ansible.parsing.vault import VaultLib, is_encrypted, is_encrypted_file, PromptVaultSecret
25 from ansible.utils.path import unfrackpath
26 from ansible.utils.display import Display
27
28 display = Display()
29
30
31 # Tries to determine if a path is inside a role, last dir must be 'tasks'
32 # this is not perfect but people should really avoid 'tasks' dirs outside roles when using Ansible.
33 RE_TASKS = re.compile('(?:^|%s)+tasks%s?$' % (os.path.sep, os.path.sep))
34
35
36 class DataLoader:
37
38 """
39 The DataLoader class is used to load and parse YAML or JSON content,
40 either from a given file name or from a string that was previously
41 read in through other means. A Vault password can be specified, and
42 any vault-encrypted files will be decrypted.
43
44 Data read from files will also be cached, so the file will never be
45 read from disk more than once.
46
47 Usage:
48
49 dl = DataLoader()
50 # optionally: dl.set_vault_secrets([('default', ansible.parsing.vault.PromptVaultSecret(...),)])
51 ds = dl.load('...')
52 ds = dl.load_from_file('/path/to/file')
53 """
54
55 def __init__(self) -> None:
56
57 self._basedir: str = os.path.abspath('.')
58
59 # NOTE: not effective with forks as the main copy does not get updated.
60 # avoids rereading files
61 self._FILE_CACHE: dict[str, object] = {}
62
63 # NOTE: not thread safe, also issues with forks not returning data to main proc
64 # so they need to be cleaned independently. See WorkerProcess for example.
65 # used to keep track of temp files for cleaning
66 self._tempfiles: set[str] = set()
67
68 # initialize the vault stuff with an empty password
69 # TODO: replace with a ref to something that can get the password
70 # a creds/auth provider
71 self._vault = VaultLib()
72 self.set_vault_secrets(None)
73
74 # TODO: since we can query vault_secrets late, we could provide this to DataLoader init
75 def set_vault_secrets(self, vault_secrets: list[tuple[str, PromptVaultSecret]] | None) -> None:
76 self._vault.secrets = vault_secrets
77
78 def load(
79 self,
80 data: str,
81 file_name: str | None = None, # DTFIX-FUTURE: consider deprecating this in favor of tagging Origin on data
82 show_content: bool = True, # DTFIX-FUTURE: consider future deprecation, but would need RedactAnnotatedSourceContext public
83 json_only: bool = False,
84 ) -> t.Any:
85 """Backwards compat for now"""
86 with _error_utils.RedactAnnotatedSourceContext.when(not show_content):
87 return from_yaml(data=data, file_name=file_name, json_only=json_only)
88
89 def load_from_file(self, file_name: str, cache: str = 'all', unsafe: bool = False, json_only: bool = False, trusted_as_template: bool = False) -> t.Any:
90 """
91 Loads data from a file, which can contain either JSON or YAML.
92
93 :param file_name: The name of the file to load data from.
94 :param cache: Options for caching: none|all|vaulted
95 :param unsafe: If True, returns the parsed data as-is without deep copying.
96 :param json_only: If True, only loads JSON data from the file.
97 :return: The loaded data, optionally deep-copied for safety.
98 """
99
100 # Resolve the file name
101 file_name = self.path_dwim(file_name)
102
103 # Log the file being loaded
104 display.debug("Loading data from %s" % file_name)
105
106 # Check if the file has been cached and use the cached data if available
107 if cache != 'none' and file_name in self._FILE_CACHE:
108 parsed_data = self._FILE_CACHE[file_name]
109 else:
110 file_data = self.get_text_file_contents(file_name)
111
112 if trusted_as_template:
113 file_data = TrustedAsTemplate().tag(file_data)
114
115 parsed_data = self.load(data=file_data, file_name=file_name, json_only=json_only)
116
117 # only tagging the container, used by include_vars to determine if vars should be shown or not
118 # this is a temporary measure until a proper data senitivity system is in place
119 if SourceWasEncrypted.is_tagged_on(file_data):
120 parsed_data = SourceWasEncrypted().tag(parsed_data)
121
122 # Cache the file contents for next time based on the cache option
123 if cache == 'all':
124 self._FILE_CACHE[file_name] = parsed_data
125 elif cache == 'vaulted' and SourceWasEncrypted.is_tagged_on(file_data):
126 self._FILE_CACHE[file_name] = parsed_data
127
128 # Return the parsed data, optionally deep-copied for safety
129 if unsafe:
130 return parsed_data
131 else:
132 return copy.deepcopy(parsed_data)
133
134 def path_exists(self, path: str) -> bool:
135 path = self.path_dwim(path)
136 return os.path.exists(path)
137
138 def is_file(self, path: str) -> bool:
139 path = self.path_dwim(path)
140 return os.path.isfile(path) or path == os.devnull
141
142 def is_directory(self, path: str) -> bool:
143 path = self.path_dwim(path)
144 return os.path.isdir(path)
145
146 def list_directory(self, path: str) -> list[str]:
147 path = self.path_dwim(path)
148 return os.listdir(path)
149
150 def is_executable(self, path: str) -> bool:
151 """is the given path executable?"""
152 path = self.path_dwim(path)
153 return is_executable(path)
154
155 def _decrypt_if_vault_data(self, b_data: bytes) -> tuple[bytes, bool]:
156 """Decrypt b_vault_data if encrypted and return b_data and the show_content flag"""
157
158 if encrypted_source := is_encrypted(b_data):
159 b_data = self._vault.decrypt(b_data)
160
161 return b_data, not encrypted_source
162
163 def get_text_file_contents(self, file_name: str, encoding: str | None = None) -> str:
164 """
165 Returns an `Origin` tagged string with the content of the specified (DWIM-expanded for relative) file path, decrypting if necessary.
166 Callers must only specify `encoding` when the user can configure it, as error messages in that case will imply configurability.
167 If `encoding` is not specified, UTF-8 will be used.
168 """
169 bytes_content, source_was_plaintext = self._get_file_contents(file_name)
170
171 if encoding is None:
172 encoding = 'utf-8'
173 help_text = 'This file must be UTF-8 encoded.'
174 else:
175 help_text = 'Ensure the correct encoding was specified.'
176
177 try:
178 str_content = bytes_content.decode(encoding=encoding, errors='strict')
179 except UnicodeDecodeError:
180 str_content = bytes_content.decode(encoding=encoding, errors='surrogateescape')
181
182 display.deprecated(
183 msg=f"File {file_name!r} could not be decoded as {encoding!r}. Invalid content has been escaped.",
184 version="2.23",
185 # obj intentionally omitted since there's no value in showing its contents
186 help_text=help_text,
187 )
188
189 if not source_was_plaintext:
190 str_content = SourceWasEncrypted().tag(str_content)
191
192 return AnsibleTagHelper.tag_copy(bytes_content, str_content)
193
194 def _get_file_contents(self, file_name: str) -> tuple[bytes, bool]:
195 """
196 Reads the file contents from the given file name
197
198 If the contents are vault-encrypted, it will decrypt them and return
199 the decrypted data
200
201 :arg file_name: The name of the file to read. If this is a relative
202 path, it will be expanded relative to the basedir
203 :raises AnsibleFileNotFound: if the file_name does not refer to a file
204 :raises AnsibleParserError: if we were unable to read the file
205 :return: Returns a byte string of the file contents
206 """
207 if not file_name or not isinstance(file_name, str):
208 raise TypeError(f"Invalid filename {file_name!r}.")
209
210 file_name = self.path_dwim(file_name)
211
212 try:
213 data = pathlib.Path(file_name).read_bytes()
214 except FileNotFoundError as ex:
215 # DTFIX-FUTURE: why not just let the builtin one fly?
216 raise AnsibleFileNotFound("Unable to retrieve file contents.", file_name=file_name) from ex
217 except OSError as ex:
218 raise AnsibleParserError(f"An error occurred while trying to read the file {file_name!r}.") from ex
219
220 data = Origin(path=file_name).tag(data)
221
222 return self._decrypt_if_vault_data(data)
223
224 def get_basedir(self) -> str:
225 """ returns the current basedir """
226 return self._basedir
227
228 def set_basedir(self, basedir: str) -> None:
229 """ sets the base directory, used to find files when a relative path is given """
230 self._basedir = os.path.abspath(basedir)
231
232 def path_dwim(self, given: str) -> str:
233 """
234 make relative paths work like folks expect.
235 """
236
237 given = unquote(given)
238
239 if given.startswith(os.path.sep) or given.startswith('~'):
240 path = given
241 else:
242 path = os.path.join(self._basedir, given)
243
244 return unfrackpath(path, follow=False)
245
246 def _is_role(self, path: str) -> bool:
247 """ imperfect role detection, roles are still valid w/o tasks|meta/main.yml|yaml|etc """
248
249 path_dirname = os.path.dirname(path)
250 upath = unfrackpath(path, follow=False)
251
252 untasked_paths = (
253 os.path.join(path, 'main.yml'),
254 os.path.join(path, 'main.yaml'),
255 os.path.join(path, 'main'),
256 )
257 tasked_paths = (
258 os.path.join(upath, 'tasks/main.yml'),
259 os.path.join(upath, 'tasks/main.yaml'),
260 os.path.join(upath, 'tasks/main'),
261 os.path.join(upath, 'meta/main.yml'),
262 os.path.join(upath, 'meta/main.yaml'),
263 os.path.join(upath, 'meta/main'),
264 os.path.join(path_dirname, 'tasks/main.yml'),
265 os.path.join(path_dirname, 'tasks/main.yaml'),
266 os.path.join(path_dirname, 'tasks/main'),
267 os.path.join(path_dirname, 'meta/main.yml'),
268 os.path.join(path_dirname, 'meta/main.yaml'),
269 os.path.join(path_dirname, 'meta/main'),
270 )
271
272 exists_untasked = map(os.path.exists, untasked_paths)
273 exists_tasked = map(os.path.exists, tasked_paths)
274 if RE_TASKS.search(path) and any(exists_untasked) or any(exists_tasked):
275 return True
276
277 return False
278
279 def path_dwim_relative(self, path: str, dirname: str, source: str, is_role: bool = False) -> str:
280 """
281 find one file in either a role or playbook dir with or without
282 explicitly named dirname subdirs
283
284 Used in action plugins and lookups to find supplemental files that
285 could be in either place.
286 """
287
288 search = []
289
290 # I have full path, nothing else needs to be looked at
291 if source.startswith(os.path.sep) or source.startswith('~'):
292 search.append(unfrackpath(source, follow=False))
293 else:
294 # base role/play path + templates/files/vars + relative filename
295 search.append(os.path.join(path, dirname, source))
296 basedir = unfrackpath(path, follow=False)
297
298 # not told if role, but detect if it is a role and if so make sure you get correct base path
299 if not is_role:
300 is_role = self._is_role(path)
301
302 if is_role and RE_TASKS.search(path):
303 basedir = unfrackpath(os.path.dirname(path), follow=False)
304
305 cur_basedir = self._basedir
306 self.set_basedir(basedir)
307 # resolved base role/play path + templates/files/vars + relative filename
308 search.append(unfrackpath(os.path.join(basedir, dirname, source), follow=False))
309 self.set_basedir(cur_basedir)
310
311 if is_role and not source.endswith(dirname):
312 # look in role's tasks dir w/o dirname
313 search.append(unfrackpath(os.path.join(basedir, 'tasks', source), follow=False))
314
315 # try to create absolute path for loader basedir + templates/files/vars + filename
316 search.append(unfrackpath(os.path.join(dirname, source), follow=False))
317
318 # try to create absolute path for loader basedir
319 search.append(unfrackpath(os.path.join(basedir, source), follow=False))
320
321 # try to create absolute path for dirname + filename
322 search.append(self.path_dwim(os.path.join(dirname, source)))
323
324 # try to create absolute path for filename
325 search.append(self.path_dwim(source))
326
327 for candidate in search:
328 if os.path.exists(candidate):
329 break
330
331 return candidate
332
333 def path_dwim_relative_stack(self, paths: list[str], dirname: str | None, source: str | None, is_role: bool = False) -> str:
334 """
335 find one file in first path in stack taking roles into account and adding play basedir as fallback
336
337 :arg paths: A list of text strings which are the paths to look for the filename in.
338 :arg dirname: A text string representing a directory. The directory
339 is prepended to the source to form the path to search for.
340 :arg source: A text string which is the filename to search for
341 :rtype: A text string
342 :returns: An absolute path to the filename ``source`` if found
343 :raises: An AnsibleFileNotFound Exception if the file is found to exist in the search paths
344 """
345 source_root = None
346 if source:
347 source_root = source.split('/')[0]
348 basedir = self.get_basedir()
349 result = None
350 search = []
351 if source is None:
352 display.warning('Invalid request to find a file that matches a "null" value')
353 elif source and (source.startswith('~') or source.startswith(os.path.sep)):
354 # path is absolute, no relative needed, check existence and return source
355 test_path = unfrackpath(source, follow=False)
356 if os.path.exists(test_path):
357 result = test_path
358 else:
359 display.debug('evaluation_path:\n\t%s' % '\n\t'.join(paths))
360 for path in paths:
361 upath = unfrackpath(path, follow=False)
362 pb_base_dir = os.path.dirname(upath)
363
364 # if path is in role and 'tasks' not there already, add it into the search
365 if (is_role or self._is_role(path)) and pb_base_dir.endswith('/tasks'):
366 if dirname:
367 search.append(os.path.join(os.path.dirname(pb_base_dir), dirname, source))
368 search.append(os.path.join(pb_base_dir, source))
369 # don't add dirname if user already is using it in source
370 if dirname and source_root != dirname:
371 search.append(os.path.join(upath, dirname, source))
372 search.append(os.path.join(upath, source))
373
374 # always append basedir as last resort
375 # don't add dirname if user already is using it in source
376 if dirname and source_root != dirname:
377 search.append(os.path.join(basedir, dirname, source))
378 search.append(os.path.join(basedir, source))
379
380 display.debug('search_path:\n\t%s' % '\n\t'.join(search))
381 for candidate in search:
382 display.vvvvv('looking for "%s" at "%s"' % (source, candidate))
383 if os.path.exists(candidate):
384 result = candidate
385 break
386
387 if result is None:
388 raise AnsibleFileNotFound(file_name=source, paths=search)
389
390 return result
391
392 def _create_content_tempfile(self, content: str | bytes) -> str:
393 """ Create a tempfile containing defined content """
394 fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
395 with os.fdopen(fd, 'wb') as f:
396 try:
397 f.write(to_bytes(content))
398 except Exception as err:
399 os.remove(content_tempfile)
400 raise Exception(err)
401 return content_tempfile
402
403 def get_real_file(self, file_path: str, decrypt: bool = True) -> str:
404 """
405 If the file is vault encrypted return a path to a temporary decrypted file
406 If the file is not encrypted then the path is returned
407 Temporary files are cleanup in the destructor
408 """
409
410 if not self.path_exists(file_path) or not self.is_file(file_path):
411 raise AnsibleFileNotFound(file_name=file_path)
412
413 real_path = self.path_dwim(file_path)
414
415 try:
416 if decrypt:
417 with open(real_path, 'rb') as f:
418 # Limit how much of the file is read since we do not know
419 # whether this is a vault file and therefore it could be very
420 # large.
421 if is_encrypted_file(f):
422 # if the file is encrypted and no password was specified,
423 # the decrypt call would throw an error, but we check first
424 # since the decrypt function doesn't know the file name
425 data = Origin(path=real_path).tag(f.read())
426 if not self._vault.secrets:
427 raise AnsibleParserError("A vault password or secret must be specified to decrypt %s" % file_path)
428
429 data = self._vault.decrypt(data)
430 # Make a temp file
431 real_path = self._create_content_tempfile(data)
432 self._tempfiles.add(real_path)
433
434 return real_path
435
436 except OSError as ex:
437 raise AnsibleParserError(f"an error occurred while trying to read the file {real_path!r}.") from ex
438
439 def cleanup_tmp_file(self, file_path: str) -> None:
440 """
441 Removes any temporary files created from a previous call to
442 get_real_file. file_path must be the path returned from a
443 previous call to get_real_file.
444 """
445 if file_path in self._tempfiles:
446 os.unlink(file_path)
447 self._tempfiles.remove(file_path)
448
449 def cleanup_all_tmp_files(self) -> None:
450 """
451 Removes all temporary files that DataLoader has created
452 NOTE: not thread safe, forks also need special handling see __init__ for details.
453 """
454 for f in list(self._tempfiles):
455 try:
456 self.cleanup_tmp_file(f)
457 except Exception as e:
458 display.warning("Unable to cleanup temp files: %s" % to_text(e))
459
460 def find_vars_files(self, path: str, name: str, extensions: list[str] | None = None, allow_dir: bool = True) -> list[str]:
461 """
462 Find vars files in a given path with specified name. This will find
463 files in a dir named <name>/ or a file called <name> ending in known
464 extensions.
465 """
466
467 jpath = os.path.join(path, name)
468 found: list[str] = []
469
470 if extensions is None:
471 # Look for file with no extension first to find dir before file
472 extensions = [''] + C.YAML_FILENAME_EXTENSIONS
473 # add valid extensions to name
474 for ext in extensions:
475
476 if '.' in ext:
477 full_path = jpath + ext
478 elif ext:
479 full_path = '.'.join([jpath, ext])
480 else:
481 full_path = jpath
482
483 if self.path_exists(full_path):
484 if self.is_directory(full_path):
485 if allow_dir:
486 found.extend(self._get_dir_vars_files(full_path, extensions))
487 else:
488 continue
489 else:
490 found.append(full_path)
491 break
492 return found
493
494 def _get_dir_vars_files(self, path: str, extensions: list[str]) -> list[str]:
495 found = []
496 for spath in sorted(self.list_directory(path)):
497 if not spath.startswith('.') and not spath.endswith('~'): # skip hidden and backups
498
499 ext = os.path.splitext(spath)[-1]
500 full_spath = os.path.join(path, spath)
501
502 if self.is_directory(full_spath) and not ext: # recursive search if dir
503 found.extend(self._get_dir_vars_files(full_spath, extensions))
504 elif self.is_file(full_spath) and (not ext or ext in extensions):
505 # only consider files with valid extensions or no extension
506 found.append(full_spath)
507
508 return found