Debian Codegraph @

lib/ansible/_internal/_templating/_transform.py

raw
1 """Runtime projections to provide template/var-visible views of objects that are not natively allowed in Ansible's type system."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import typing as t
7
8 from ansible.module_utils._internal import _traceback, _event_utils, _messages
9 from ansible.parsing.vault import EncryptedString, VaultHelper
10 from ansible.utils.display import Display
11
12 from ._jinja_common import VaultExceptionMarker
13 from .._errors import _captured, _error_factory
14 from .. import _event_formatting
15
16 display = Display()
17
18
19 def plugin_info(value: _messages.PluginInfo) -> dict[str, str]:
20 """Render PluginInfo as a dictionary."""
21 return dataclasses.asdict(value)
22
23
24 def plugin_type(value: _messages.PluginType) -> str:
25 """Render PluginType as a string."""
26 return value.value
27
28
29 def error_summary(value: _messages.ErrorSummary) -> str:
30 """Render ErrorSummary as a formatted traceback for backward-compatibility with pre-2.19 TaskResult.exception."""
31 if _traceback._is_traceback_enabled(_traceback.TracebackEvent.ERROR):
32 return _event_formatting.format_event_traceback(value.event)
33
34 return '(traceback unavailable)'
35
36
37 def warning_summary(value: _messages.WarningSummary) -> str:
38 """Render WarningSummary as a simple message string for backward-compatibility with pre-2.19 TaskResult.warnings."""
39 return _event_utils.format_event_brief_message(value.event)
40
41
42 def deprecation_summary(value: _messages.DeprecationSummary) -> dict[str, t.Any]:
43 """Render DeprecationSummary as dict values for backward-compatibility with pre-2.19 TaskResult.deprecations."""
44 transformed = _event_utils.deprecation_as_dict(value)
45 transformed.update(deprecator=value.deprecator)
46
47 return transformed
48
49
50 def encrypted_string(value: EncryptedString) -> str | VaultExceptionMarker:
51 """Decrypt an encrypted string and return its value, or a VaultExceptionMarker if decryption fails."""
52 try:
53 return value._decrypt()
54 except Exception as ex:
55 return VaultExceptionMarker(
56 ciphertext=VaultHelper.get_ciphertext(value, with_tags=True),
57 event=_error_factory.ControllerEventFactory.from_exception(ex, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)),
58 )
59
60
61 _type_transform_mapping: dict[type, t.Callable[[t.Any], t.Any]] = {
62 _captured.CapturedErrorSummary: error_summary,
63 _messages.PluginInfo: plugin_info,
64 _messages.PluginType: plugin_type,
65 _messages.ErrorSummary: error_summary,
66 _messages.WarningSummary: warning_summary,
67 _messages.DeprecationSummary: deprecation_summary,
68 EncryptedString: encrypted_string,
69 }
70 """This mapping is consulted by `Templar.template` to provide custom views of some objects."""