| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import ast |
| 4 |
import collections.abc as c |
| 5 |
import dataclasses |
| 6 |
import enum |
| 7 |
import pathlib |
| 8 |
import tempfile |
| 9 |
import types |
| 10 |
import typing as t |
| 11 |
|
| 12 |
from collections import ChainMap |
| 13 |
|
| 14 |
import jinja2.nodes |
| 15 |
|
| 16 |
from jinja2 import pass_context, defaults, TemplateSyntaxError, FileSystemLoader |
| 17 |
from jinja2.environment import Environment, Template, TemplateModule, TemplateExpression |
| 18 |
from jinja2.compiler import Frame |
| 19 |
from jinja2.lexer import TOKEN_VARIABLE_BEGIN, TOKEN_VARIABLE_END, TOKEN_STRING, Lexer |
| 20 |
from jinja2.nativetypes import NativeCodeGenerator |
| 21 |
from jinja2.nodes import Const, EvalContext |
| 22 |
from jinja2.runtime import Context, Macro |
| 23 |
from jinja2.sandbox import SandboxedEnvironment |
| 24 |
from jinja2.utils import missing, LRUCache |
| 25 |
|
| 26 |
from ansible.utils.display import Display |
| 27 |
from ansible.errors import AnsibleVariableTypeError, AnsibleTemplateSyntaxError, AnsibleTemplateError |
| 28 |
from ansible.module_utils.common.text.converters import to_text |
| 29 |
from ansible.module_utils._internal._datatag import ( |
| 30 |
_AnsibleTaggedDict, |
| 31 |
_AnsibleTaggedList, |
| 32 |
_AnsibleTaggedTuple, |
| 33 |
_AnsibleTaggedStr, |
| 34 |
AnsibleTagHelper, |
| 35 |
) |
| 36 |
|
| 37 |
from ansible._internal._errors import _error_utils |
| 38 |
from ansible._internal._errors._handler import ErrorAction |
| 39 |
from ansible._internal._datatag._tags import Origin, TrustedAsTemplate |
| 40 |
|
| 41 |
from ._access import AnsibleAccessContext |
| 42 |
from ._datatag import _JinjaConstTemplate |
| 43 |
from ._utils import LazyOptions |
| 44 |
from ._jinja_common import ( |
| 45 |
MarkerError, |
| 46 |
Marker, |
| 47 |
CapturedExceptionMarker, |
| 48 |
UndefinedMarker, |
| 49 |
_TemplateConfig, |
| 50 |
TruncationMarker, |
| 51 |
validate_arg_type, |
| 52 |
JinjaCallContext, |
| 53 |
_SandboxMode, |
| 54 |
) |
| 55 |
from ._jinja_plugins import JinjaPluginIntercept, _query, _lookup, _now, _wrap_plugin_output, get_first_marker_arg, _DirectCall, _jinja_const_template_warning |
| 56 |
from ._lazy_containers import ( |
| 57 |
_AnsibleLazyTemplateMixin, |
| 58 |
_AnsibleLazyTemplateDict, |
| 59 |
_AnsibleLazyTemplateList, |
| 60 |
_AnsibleLazyAccessTuple, |
| 61 |
lazify_container_args, |
| 62 |
lazify_container_kwargs, |
| 63 |
lazify_container, |
| 64 |
register_known_types, |
| 65 |
) |
| 66 |
from ._utils import Omit, TemplateContext, PASS_THROUGH_SCALAR_VAR_TYPES |
| 67 |
|
| 68 |
from ansible.module_utils._internal._json._profiles import _json_subclassable_scalar_types |
| 69 |
from ansible.module_utils import _internal |
| 70 |
from ansible.module_utils._internal import _ambient_context, _dataclass_validation |
| 71 |
from ansible.plugins.loader import filter_loader, test_loader |
| 72 |
from ansible.vars.hostvars import HostVars, HostVarsVars |
| 73 |
from .._errors import _attribute_unavailable |
| 74 |
from ...module_utils.datatag import native_type_name |
| 75 |
|
| 76 |
JINJA2_OVERRIDE = '#jinja2:' |
| 77 |
""" |
| 78 |
String values prefixed with this sequence are interpreted as templates, even without template delimiters. |
| 79 |
The values following this prefix up to the first newline are parsed as Jinja2 template overrides. |
| 80 |
To include this literal value at the start of a string, a space or other character must precede it. |
| 81 |
""" |
| 82 |
|
| 83 |
JINJA_KEYWORDS = frozenset( |
| 84 |
{ |
| 85 |
# scalar singletons (see jinja2.nodes.Name.can_assign) |
| 86 |
'true', |
| 87 |
'false', |
| 88 |
'none', |
| 89 |
'True', |
| 90 |
'False', |
| 91 |
'None', |
| 92 |
# other |
| 93 |
'not', # unary operator always applicable to names |
| 94 |
} |
| 95 |
) |
| 96 |
"""Names which have special meaning to Jinja and cannot be resolved as variable names.""" |
| 97 |
|
| 98 |
display = Display() |
| 99 |
|
| 100 |
|
| 101 |
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True) |
| 102 |
class TemplateOverrides: |
| 103 |
DEFAULT: t.ClassVar[t.Self] |
| 104 |
|
| 105 |
block_start_string: str = defaults.BLOCK_START_STRING |
| 106 |
block_end_string: str = defaults.BLOCK_END_STRING |
| 107 |
variable_start_string: str = defaults.VARIABLE_START_STRING |
| 108 |
variable_end_string: str = defaults.VARIABLE_END_STRING |
| 109 |
comment_start_string: str = defaults.COMMENT_START_STRING |
| 110 |
comment_end_string: str = defaults.COMMENT_END_STRING |
| 111 |
line_statement_prefix: str | None = defaults.LINE_STATEMENT_PREFIX |
| 112 |
line_comment_prefix: str | None = defaults.LINE_COMMENT_PREFIX |
| 113 |
trim_blocks: bool = True # AnsibleEnvironment overrides this default, so don't use the Jinja default here |
| 114 |
lstrip_blocks: bool = defaults.LSTRIP_BLOCKS |
| 115 |
newline_sequence: t.Literal['\n', '\r\n', '\r'] = defaults.NEWLINE_SEQUENCE |
| 116 |
keep_trailing_newline: bool = defaults.KEEP_TRAILING_NEWLINE |
| 117 |
|
| 118 |
def __post_init__(self) -> None: |
| 119 |
pass # overridden by _dataclass_validation._inject_post_init_validation |
| 120 |
|
| 121 |
def _post_validate(self) -> None: |
| 122 |
if not (self.block_start_string != self.variable_start_string != self.comment_start_string != self.block_start_string): |
| 123 |
raise ValueError('Block, variable and comment start strings must be different.') |
| 124 |
|
| 125 |
def overlay_kwargs(self) -> dict[str, t.Any]: |
| 126 |
""" |
| 127 |
Return a dictionary of arguments for passing to Environment.overlay. |
| 128 |
The dictionary will be empty if all fields have their default value. |
| 129 |
""" |
| 130 |
# DTFIX-FUTURE: calculate default/non-default during __post_init__ |
| 131 |
fields = [(field, getattr(self, field.name)) for field in dataclasses.fields(self)] |
| 132 |
kwargs = {field.name: value for field, value in fields if value != field.default} |
| 133 |
|
| 134 |
return kwargs |
| 135 |
|
| 136 |
def _contains_start_string(self, value: str) -> bool: |
| 137 |
"""Returns True if the given value contains a variable, block or comment start string.""" |
| 138 |
# DTFIX-FUTURE: this is inefficient, use a compiled regex instead |
| 139 |
|
| 140 |
for marker in (self.block_start_string, self.variable_start_string, self.comment_start_string): |
| 141 |
if marker in value: |
| 142 |
return True |
| 143 |
|
| 144 |
return False |
| 145 |
|
| 146 |
def _starts_and_ends_with_jinja_delimiters(self, value: str) -> bool: |
| 147 |
"""Returns True if the given value starts and ends with Jinja variable, block or comment delimiters.""" |
| 148 |
# DTFIX-FUTURE: this is inefficient, use a compiled regex instead |
| 149 |
|
| 150 |
for marker in (self.block_start_string, self.variable_start_string, self.comment_start_string): |
| 151 |
if value.startswith(marker): |
| 152 |
break |
| 153 |
else: |
| 154 |
return False |
| 155 |
|
| 156 |
for marker in (self.block_end_string, self.variable_end_string, self.comment_end_string): |
| 157 |
if value.endswith(marker): |
| 158 |
return True |
| 159 |
|
| 160 |
return False |
| 161 |
|
| 162 |
def _extract_template_overrides(self, template: str) -> tuple[str, TemplateOverrides]: |
| 163 |
if template.startswith(JINJA2_OVERRIDE): |
| 164 |
eol = template.find('\n') |
| 165 |
|
| 166 |
if eol == -1: |
| 167 |
raise ValueError(f"Missing newline after {JINJA2_OVERRIDE!r} override.") |
| 168 |
|
| 169 |
line = template[len(JINJA2_OVERRIDE) : eol] |
| 170 |
template = template[eol + 1 :] |
| 171 |
override_kwargs = {} |
| 172 |
|
| 173 |
for pair in line.split(','): |
| 174 |
if not pair.strip(): |
| 175 |
raise ValueError(f"Empty {JINJA2_OVERRIDE!r} override pair not allowed.") |
| 176 |
|
| 177 |
if ':' not in pair: |
| 178 |
raise ValueError(f"Missing key-value separator `:` in {JINJA2_OVERRIDE!r} override pair {pair!r}.") |
| 179 |
|
| 180 |
key, val = pair.split(':', 1) |
| 181 |
key = key.strip() |
| 182 |
|
| 183 |
if key not in _TEMPLATE_OVERRIDE_FIELD_NAMES: |
| 184 |
raise ValueError(f"Invalid {JINJA2_OVERRIDE!r} override key {key!r}.") |
| 185 |
|
| 186 |
override_kwargs[key] = ast.literal_eval(val) |
| 187 |
|
| 188 |
overrides = dataclasses.replace(self, **override_kwargs) |
| 189 |
else: |
| 190 |
overrides = self |
| 191 |
|
| 192 |
return template, overrides |
| 193 |
|
| 194 |
def merge(self, kwargs: dict[str, t.Any] | None, /) -> TemplateOverrides: |
| 195 |
"""Return a new instance based on the current instance with the given kwargs overridden.""" |
| 196 |
if kwargs: |
| 197 |
return self.from_kwargs(dataclasses.asdict(self) | kwargs) |
| 198 |
|
| 199 |
return self |
| 200 |
|
| 201 |
@classmethod |
| 202 |
def from_kwargs(cls, kwargs: dict[str, t.Any] | None, /) -> TemplateOverrides: |
| 203 |
"""TemplateOverrides instance factory; instances resolving to all default values will instead return the DEFAULT singleton for optimization.""" |
| 204 |
if kwargs: |
| 205 |
value = cls(**kwargs) |
| 206 |
|
| 207 |
if value.overlay_kwargs(): |
| 208 |
return value |
| 209 |
|
| 210 |
return cls.DEFAULT |
| 211 |
|
| 212 |
|
| 213 |
_dataclass_validation.inject_post_init_validation(TemplateOverrides, allow_subclasses=True) |
| 214 |
|
| 215 |
TemplateOverrides.DEFAULT = TemplateOverrides() |
| 216 |
|
| 217 |
_TEMPLATE_OVERRIDE_FIELD_NAMES: t.Final[tuple[str, ...]] = tuple(sorted(field.name for field in dataclasses.fields(TemplateOverrides))) |
| 218 |
|
| 219 |
|
| 220 |
class AnsibleContext(Context): |
| 221 |
""" |
| 222 |
A custom context which intercepts resolve_or_missing() calls and |
| 223 |
runs them through AnsibleAccessContext. This allows usage of variables |
| 224 |
to be tracked. If needed, values can also be modified before being returned. |
| 225 |
""" |
| 226 |
|
| 227 |
environment: AnsibleEnvironment # narrow the type specified by the base |
| 228 |
|
| 229 |
def __init__(self, *args, **kwargs): |
| 230 |
super(AnsibleContext, self).__init__(*args, **kwargs) |
| 231 |
|
| 232 |
__repr__ = object.__repr__ # prevent Jinja from dumping vars in case this gets repr'd |
| 233 |
|
| 234 |
def get_all(self): |
| 235 |
""" |
| 236 |
Override Jinja's default get_all to return all vars in the context as a ChainMap with a mutable layer at the bottom. |
| 237 |
This provides some isolation against accidental changes to inherited variable contexts without requiring copies. |
| 238 |
""" |
| 239 |
layers = [] |
| 240 |
|
| 241 |
if self.vars: |
| 242 |
layers.append(self.vars) |
| 243 |
if self.parent: |
| 244 |
layers.append(self.parent) |
| 245 |
|
| 246 |
# HACK: always include a sacrificial plain-dict on the bottom layer, since Jinja's debug and stacktrace rewrite code invokes |
| 247 |
# `__setitem__` outside a call context; this will ensure that it always occurs on a plain dict instead of a lazy one. |
| 248 |
return ChainMap({}, *layers) |
| 249 |
|
| 250 |
# noinspection PyShadowingBuiltins |
| 251 |
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> Context: |
| 252 |
# this is a clone of Jinja's impl of derived, but using our lazy-aware _new_context |
| 253 |
|
| 254 |
context = _new_context( |
| 255 |
environment=self.environment, |
| 256 |
template_name=self.name, |
| 257 |
blocks={}, |
| 258 |
shared=True, |
| 259 |
jinja_locals=locals, |
| 260 |
jinja_vars=self.get_all(), |
| 261 |
) |
| 262 |
context.eval_ctx = self.eval_ctx |
| 263 |
context.blocks.update((k, list(v)) for k, v in self.blocks.items()) |
| 264 |
return context |
| 265 |
|
| 266 |
def keys(self, *args, **kwargs): |
| 267 |
"""Base Context delegates to `dict.keys` against `get_all`, which would fail since we return a ChainMap. No known usage.""" |
| 268 |
raise NotImplementedError() |
| 269 |
|
| 270 |
def values(self, *args, **kwargs): |
| 271 |
"""Base Context delegates to `dict.values` against `get_all`, which would fail since we return a ChainMap. No known usage.""" |
| 272 |
raise NotImplementedError() |
| 273 |
|
| 274 |
def items(self, *args, **kwargs): |
| 275 |
"""Base Context delegates to built-in `dict.items` against `get_all`, which would fail since we return a ChainMap. No known usage.""" |
| 276 |
raise NotImplementedError() |
| 277 |
|
| 278 |
|
| 279 |
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True) |
| 280 |
class ArgSmuggler: |
| 281 |
""" |
| 282 |
Utility wrapper to wrap/unwrap args passed to Jinja `Template.render` and `TemplateExpression.__call__`. |
| 283 |
e.g., see https://github.com/pallets/jinja/blob/3.1.3/src/jinja2/environment.py#L1296 and |
| 284 |
https://github.com/pallets/jinja/blob/3.1.3/src/jinja2/environment.py#L1566. |
| 285 |
""" |
| 286 |
|
| 287 |
jinja_vars: c.Mapping[str, t.Any] | None |
| 288 |
|
| 289 |
@classmethod |
| 290 |
def package_jinja_vars(cls, jinja_vars: c.Mapping[str, t.Any]) -> dict[str, ArgSmuggler]: |
| 291 |
"""Wrap the supplied vars dict in an ArgSmuggler to prevent premature templating from Jinja's internal dict copy.""" |
| 292 |
return dict(_smuggled_vars=ArgSmuggler(jinja_vars=jinja_vars)) |
| 293 |
|
| 294 |
@classmethod |
| 295 |
def extract_jinja_vars(cls, maybe_smuggled_vars: c.Mapping[str, t.Any] | None) -> c.Mapping[str, t.Any]: |
| 296 |
""" |
| 297 |
If the supplied vars dict contains an ArgSmuggler instance with the expected key, unwrap it and return the smuggled value. |
| 298 |
Otherwise, return the supplied dict as-is. |
| 299 |
""" |
| 300 |
if maybe_smuggled_vars and ((smuggler := maybe_smuggled_vars.get('_smuggled_vars')) and isinstance(smuggler, ArgSmuggler)): |
| 301 |
return smuggler.jinja_vars |
| 302 |
|
| 303 |
return maybe_smuggled_vars |
| 304 |
|
| 305 |
|
| 306 |
class AnsibleTemplateExpression: |
| 307 |
""" |
| 308 |
Wrapper around Jinja's TemplateExpression for converting MarkerError back into Marker. |
| 309 |
This is needed to make expression error handling consistent with templates, since Jinja does not support a custom type for Environment.compile_expression. |
| 310 |
""" |
| 311 |
|
| 312 |
def __init__(self, template_expression: TemplateExpression) -> None: |
| 313 |
self._template_expression = template_expression |
| 314 |
|
| 315 |
def __call__(self, jinja_vars: c.Mapping[str, t.Any]) -> t.Any: |
| 316 |
try: |
| 317 |
return self._template_expression(ArgSmuggler.package_jinja_vars(jinja_vars)) |
| 318 |
except MarkerError as ex: |
| 319 |
return ex.source |
| 320 |
|
| 321 |
|
| 322 |
class AnsibleTemplate(Template): |
| 323 |
""" |
| 324 |
A helper class, which prevents Jinja2 from running lazy containers through dict(). |
| 325 |
""" |
| 326 |
|
| 327 |
_python_source_temp_path: pathlib.Path | None = None |
| 328 |
|
| 329 |
def __del__(self): |
| 330 |
# DTFIX-FUTURE: this still isn't working reliably; something else must be keeping the template object alive |
| 331 |
if self._python_source_temp_path: |
| 332 |
self._python_source_temp_path.unlink(missing_ok=True) |
| 333 |
|
| 334 |
def __call__(self, jinja_vars: c.Mapping[str, t.Any]) -> t.Any: |
| 335 |
return self.render(ArgSmuggler.package_jinja_vars(jinja_vars)) |
| 336 |
|
| 337 |
def __deepcopy__(self, memo): |
| 338 |
return self # templates are immutable, so a deep copy is not needed (it would also fail if not implemented here) |
| 339 |
|
| 340 |
# noinspection PyShadowingBuiltins |
| 341 |
def new_context( |
| 342 |
self, |
| 343 |
vars: c.Mapping[str, t.Any] | None = None, |
| 344 |
shared: bool = False, |
| 345 |
locals: c.Mapping[str, t.Any] | None = None, |
| 346 |
) -> Context: |
| 347 |
return _new_context( |
| 348 |
environment=self.environment, |
| 349 |
template_name=self.name, |
| 350 |
blocks=self.blocks, |
| 351 |
shared=shared, |
| 352 |
jinja_locals=locals, |
| 353 |
jinja_vars=ArgSmuggler.extract_jinja_vars(vars), |
| 354 |
jinja_globals=self.globals, |
| 355 |
) |
| 356 |
|
| 357 |
|
| 358 |
class AnsibleCodeGenerator(NativeCodeGenerator): |
| 359 |
""" |
| 360 |
Custom code generation behavior to support deprecated Ansible features and fill in gaps in Jinja native. |
| 361 |
This can be removed once the deprecated Ansible features are removed and the native fixes are upstreamed in Jinja. |
| 362 |
""" |
| 363 |
|
| 364 |
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: |
| 365 |
""" |
| 366 |
Prevent Jinja's code generation from stringifying single nodes before generating its repr. |
| 367 |
This complements the behavioral change in AnsibleEnvironment.concat which returns single nodes without stringifying them. |
| 368 |
""" |
| 369 |
# DTFIX-FUTURE: contribute this upstream as a fix to Jinja's native support |
| 370 |
group_list = list(group) |
| 371 |
|
| 372 |
if len(group_list) == 1: |
| 373 |
return repr(group_list[0]) |
| 374 |
|
| 375 |
# NB: This is slightly more efficient than Jinja's _output_const_repr, which generates a throw-away list instance to pass to join. |
| 376 |
# Before removing this, ensure that upstream Jinja has this change. |
| 377 |
return repr("".join(map(str, group_list))) |
| 378 |
|
| 379 |
def visit_Const(self, node: Const, frame: Frame) -> None: |
| 380 |
""" |
| 381 |
Override Jinja's visit_Const to inject a runtime call to AnsibleEnvironment._access_const for constant strings that are possibly templates, which |
| 382 |
may require special handling at runtime. See that method for details. An example that hits this path: |
| 383 |
{{ lookup("file", "{{ output_dir }}/bla") }} |
| 384 |
""" |
| 385 |
value = node.as_const(frame.eval_ctx) |
| 386 |
|
| 387 |
if _TemplateConfig.allow_embedded_templates and type(value) is str and is_possibly_template(value): # pylint: disable=unidiomatic-typecheck |
| 388 |
# deprecated: description='embedded Jinja constant string template support' core_version='2.23' |
| 389 |
self.write(f'environment._access_const({value!r})') |
| 390 |
else: |
| 391 |
# NB: This is actually more efficient than Jinja's visit_Const, which contains obsolete (as of Py2.7/3.1) float conversion instance checks. Before |
| 392 |
# removing this override entirely, ensure that upstream Jinja has removed the obsolete code. |
| 393 |
# See https://docs.python.org/release/2.7/whatsnew/2.7.html#python-3-1-features for more details. |
| 394 |
self.write(repr(value)) |
| 395 |
|
| 396 |
|
| 397 |
@pass_context |
| 398 |
def _ansible_finalize(_ctx: AnsibleContext, value: t.Any) -> t.Any: |
| 399 |
""" |
| 400 |
This function is called by Jinja with the result of each variable template block (e.g., {{ }}) encountered in a template. |
| 401 |
The pass_context decorator prevents finalize from being called on constants at template compile time. |
| 402 |
The passed in AnsibleContext is unused -- it is the result of using the pass_context decorator. |
| 403 |
The important part for us is that this blocks constant folding, which ensures our custom visit_Const is used. |
| 404 |
It also ensures that template results are wrapped in lazy containers. |
| 405 |
""" |
| 406 |
return lazify_container(value) |
| 407 |
|
| 408 |
|
| 409 |
@dataclasses.dataclass(kw_only=True, slots=True) |
| 410 |
class _TemplateCompileContext(_ambient_context.AmbientContextBase): |
| 411 |
""" |
| 412 |
This context is active during Ansible's explicit compilation of templates/expressions, but not during Jinja's runtime compilation. |
| 413 |
Historically, Ansible-specific pre-processing like `escape_backslashes` was not applied to imported/included templates. |
| 414 |
""" |
| 415 |
|
| 416 |
escape_backslashes: bool |
| 417 |
|
| 418 |
|
| 419 |
class _CompileStateSmugglingCtx(_ambient_context.AmbientContextBase): |
| 420 |
template_source: str | None = None |
| 421 |
python_source: str | None = None |
| 422 |
python_source_temp_path: pathlib.Path | None = None |
| 423 |
|
| 424 |
|
| 425 |
class AnsibleLexer(Lexer): |
| 426 |
""" |
| 427 |
Lexer override to escape backslashes in string constants within Jinja expressions; prevents Jinja from double-escaping them. |
| 428 |
|
| 429 |
NOTE: This behavior is only applied to string constants within Jinja expressions (eg {{ "c:\newfile" }}), *not* statements ("{% set foo="c:\\newfile" %}"). |
| 430 |
|
| 431 |
This is useful when templates are sourced from YAML double-quoted strings, as it avoids having backslashes processed twice: first by the |
| 432 |
YAML parser, and then again by the Jinja parser. Instead, backslashes are only processed by YAML. |
| 433 |
|
| 434 |
Example YAML: |
| 435 |
|
| 436 |
- debug: |
| 437 |
msg: "Test Case 1\\3; {{ test1_name | regex_replace('^(.*)_name$', '\\1')}}" |
| 438 |
|
| 439 |
Since the outermost YAML string is double-quoted, the YAML parser converts the double backslashes to single backslashes. Without escaping, Jinja |
| 440 |
would see only a single backslash ('\1') while processing the embedded template expression, interpret it as an escape sequence, and convert it |
| 441 |
to '\x01' (ASCII "SOH"). This is clearly not the intended `\1` backreference argument to the `regex_replace` filter (which would require the |
| 442 |
double-escaped string '\\\\1' to yield the intended result). |
| 443 |
|
| 444 |
Since the "\\3" in the input YAML was not part of a template expression, the YAML-parsed "\3" remains after Jinja rendering. This would be |
| 445 |
confusing for playbook authors, as different escaping rules would be needed inside and outside the template expression. |
| 446 |
|
| 447 |
When templates are not sourced from YAML, escaping backslashes will prevent use of backslash escape sequences such as "\n" and "\t". |
| 448 |
|
| 449 |
See relevant Jinja lexer impl at e.g.: https://github.com/pallets/jinja/blob/3.1.2/src/jinja2/lexer.py#L646-L653. |
| 450 |
""" |
| 451 |
|
| 452 |
def tokeniter(self, *args, **kwargs) -> t.Iterator[t.Tuple[int, str, str]]: |
| 453 |
"""Pre-escape backslashes in expression ({{ }}) raw string constants before Jinja's Lexer.wrap() can interpret them as ASCII escape sequences.""" |
| 454 |
token_stream = super().tokeniter(*args, **kwargs) |
| 455 |
|
| 456 |
# if we have no context, Jinja's doing a nested compile at runtime (eg, import/include); historically, no backslash escaping is performed |
| 457 |
if not (tcc := _TemplateCompileContext.current(optional=True)) or not tcc.escape_backslashes: |
| 458 |
yield from token_stream |
| 459 |
return |
| 460 |
|
| 461 |
in_variable = False |
| 462 |
|
| 463 |
for token in token_stream: |
| 464 |
token_type = token[1] |
| 465 |
|
| 466 |
if token_type == TOKEN_VARIABLE_BEGIN: |
| 467 |
in_variable = True |
| 468 |
elif token_type == TOKEN_VARIABLE_END: |
| 469 |
in_variable = False |
| 470 |
elif in_variable and token_type == TOKEN_STRING: |
| 471 |
token = token[0], token_type, token[2].replace('\\', '\\\\') |
| 472 |
|
| 473 |
yield token |
| 474 |
|
| 475 |
|
| 476 |
def defer_template_error(ex: Exception, variable: t.Any, *, is_expression: bool) -> Marker: |
| 477 |
if not ex.__traceback__: |
| 478 |
raise AssertionError('ex must be a previously raised exception') |
| 479 |
|
| 480 |
if isinstance(ex, MarkerError): |
| 481 |
return ex.source |
| 482 |
|
| 483 |
exception_to_raise = create_template_error(ex, variable, is_expression) |
| 484 |
|
| 485 |
if exception_to_raise is ex: |
| 486 |
return CapturedExceptionMarker(ex) # capture the previously raised exception |
| 487 |
|
| 488 |
try: |
| 489 |
raise exception_to_raise from ex # raise the newly synthesized exception before capturing it |
| 490 |
except Exception as captured_ex: |
| 491 |
return CapturedExceptionMarker(captured_ex) |
| 492 |
|
| 493 |
|
| 494 |
def create_template_error(ex: Exception, variable: t.Any, is_expression: bool) -> AnsibleTemplateError: |
| 495 |
if isinstance(ex, AnsibleTemplateError): |
| 496 |
exception_to_raise = ex |
| 497 |
else: |
| 498 |
kind = "expression" if is_expression else "template" |
| 499 |
ex_type = AnsibleTemplateError # always raise an AnsibleTemplateError/subclass |
| 500 |
|
| 501 |
if isinstance(ex, RecursionError): |
| 502 |
msg = f"Recursive loop detected in {kind}." |
| 503 |
elif isinstance(ex, TemplateSyntaxError): |
| 504 |
if (origin := Origin.get_tag(variable)) and origin.line_num is None and ex.lineno > 0: |
| 505 |
# When there is an origin without a line number, use the line number provided by the Jinja syntax error. |
| 506 |
# This should only occur on templates which represent the entire contents of a file. |
| 507 |
# Templates loaded from within a file, such as YAML, will use the existing origin. |
| 508 |
# It's not possible to combine origins here, due to potential layout differences between the original content and the parsed output. |
| 509 |
# This can happen, for example, with YAML multi-line strings. |
| 510 |
variable = origin.replace(line_num=ex.lineno, col_num=None).tag(variable) |
| 511 |
|
| 512 |
msg = f"Syntax error in {kind}." |
| 513 |
|
| 514 |
if is_expression and is_possibly_template(variable): |
| 515 |
msg += " Template delimiters are not supported in expressions." |
| 516 |
|
| 517 |
ex_type = AnsibleTemplateSyntaxError |
| 518 |
else: |
| 519 |
msg = f"Error rendering {kind}." |
| 520 |
|
| 521 |
exception_to_raise = ex_type(msg, obj=variable) |
| 522 |
|
| 523 |
if exception_to_raise.obj is None: |
| 524 |
exception_to_raise.obj = TemplateContext.current().template_value |
| 525 |
|
| 526 |
# DTFIX-FUTURE: Look through the TemplateContext hierarchy to find the most recent non-template |
| 527 |
# caller and use that for origin when no origin is available on obj. This could be useful for situations where the template |
| 528 |
# was embedded in a plugin, or a plugin is otherwise responsible for losing the origin and/or trust. We can't just use the first |
| 529 |
# non-template caller as that will lead to false positives for re-entrant calls (e.g. template plugins that call into templar). |
| 530 |
|
| 531 |
return exception_to_raise |
| 532 |
|
| 533 |
|
| 534 |
_BUILTIN_FILTER_ALIASES: dict[str, str] = {} |
| 535 |
_BUILTIN_TEST_ALIASES: dict[str, str] = { |
| 536 |
'!=': 'ne', |
| 537 |
'<': 'lt', |
| 538 |
'<=': 'le', |
| 539 |
'==': 'eq', |
| 540 |
'>': 'gt', |
| 541 |
'>=': 'ge', |
| 542 |
} |
| 543 |
|
| 544 |
_BUILTIN_FILTERS = filter_loader._wrap_funcs(defaults.DEFAULT_FILTERS, _BUILTIN_FILTER_ALIASES) |
| 545 |
_BUILTIN_TESTS = test_loader._wrap_funcs(t.cast(dict[str, t.Callable], defaults.DEFAULT_TESTS), _BUILTIN_TEST_ALIASES) |
| 546 |
|
| 547 |
|
| 548 |
class AnsibleEnvironment(SandboxedEnvironment): |
| 549 |
""" |
| 550 |
Our custom environment, which simply allows us to override the class-level |
| 551 |
values for the Template and Context classes used by jinja2 internally. |
| 552 |
""" |
| 553 |
|
| 554 |
context_class = AnsibleContext |
| 555 |
template_class = AnsibleTemplate |
| 556 |
code_generator_class = AnsibleCodeGenerator |
| 557 |
intercepted_binops = frozenset(('eq',)) |
| 558 |
|
| 559 |
_allowed_unsafe_attributes: dict[str, type | tuple[type, ...]] = dict( |
| 560 |
# Allow bitwise operations on int until bitwise filters are available. |
| 561 |
# see: https://github.com/ansible/ansible/issues/85204 |
| 562 |
__and__=int, |
| 563 |
__lshift__=int, |
| 564 |
__or__=int, |
| 565 |
__rshift__=int, |
| 566 |
__xor__=int, |
| 567 |
) |
| 568 |
""" |
| 569 |
Attributes which are considered unsafe by `is_safe_attribute`, which should be allowed when used on specific types. |
| 570 |
The attributes allowed here are intended only for backward compatibility with existing use cases. |
| 571 |
They should be exposed as filters in a future release and eventually deprecated. |
| 572 |
""" |
| 573 |
|
| 574 |
_lexer_cache = LRUCache(50) |
| 575 |
|
| 576 |
# DTFIX-FUTURE: bikeshed a name/mechanism to control template debugging |
| 577 |
_debuggable_template_source = False |
| 578 |
_debuggable_template_source_path: pathlib.Path = pathlib.Path(__file__).parent.parent.parent.parent / '.template_debug_source' |
| 579 |
|
| 580 |
def __init__(self, *args, ansible_basedir: str | None = None, **kwargs) -> None: |
| 581 |
if ansible_basedir: |
| 582 |
kwargs.update(loader=FileSystemLoader(ansible_basedir)) |
| 583 |
|
| 584 |
super().__init__(*args, extensions=_TemplateConfig.jinja_extensions, **kwargs) |
| 585 |
|
| 586 |
self.filters = JinjaPluginIntercept(_BUILTIN_FILTERS, filter_loader) # type: ignore[assignment] |
| 587 |
self.tests = JinjaPluginIntercept(_BUILTIN_TESTS, test_loader) # type: ignore[assignment,arg-type] |
| 588 |
|
| 589 |
# future Jinja releases may default-enable autoescape; force-disable to prevent the problems it could cause |
| 590 |
# see https://github.com/pallets/jinja/blob/3.1.2/docs/api.rst?plain=1#L69 |
| 591 |
self.autoescape = False |
| 592 |
|
| 593 |
self.trim_blocks = True |
| 594 |
|
| 595 |
self.undefined = UndefinedMarker |
| 596 |
self.finalize = _ansible_finalize |
| 597 |
|
| 598 |
self.globals.update( |
| 599 |
range=range, # the sandboxed environment limits range in ways that may cause us problems; use the real Python one |
| 600 |
now=_now, |
| 601 |
undef=_undef, |
| 602 |
omit=Omit, |
| 603 |
lookup=_lookup, |
| 604 |
query=_query, |
| 605 |
q=_query, |
| 606 |
) |
| 607 |
|
| 608 |
# Disabling the optimizer prevents compile-time constant expression folding, which prevents our |
| 609 |
# visit_Const recursive inline template expansion tricks from working in many cases where Jinja's |
| 610 |
# ignorance of our embedded templates are optimized away as fully-constant expressions, |
| 611 |
# eg {{ "{{'hi'}}" == "hi" }}. As of Jinja ~3.1, this specifically avoids cases where the @optimizeconst |
| 612 |
# visitor decorator performs constant folding, which bypasses our visit_Const impl and causes embedded |
| 613 |
# templates to be lost. |
| 614 |
# See also optimizeconst impl: https://github.com/pallets/jinja/blob/3.1.0/src/jinja2/compiler.py#L48-L49 |
| 615 |
self.optimized = False |
| 616 |
|
| 617 |
def get_template( |
| 618 |
self, |
| 619 |
name: str | Template, |
| 620 |
parent: str | None = None, |
| 621 |
globals: c.MutableMapping[str, t.Any] | None = None, |
| 622 |
) -> Template: |
| 623 |
"""Ensures that templates built via `get_template` are also source debuggable.""" |
| 624 |
with _CompileStateSmugglingCtx.when(self._debuggable_template_source) as ctx: |
| 625 |
template_obj = t.cast(AnsibleTemplate, super().get_template(name, parent, globals)) |
| 626 |
|
| 627 |
if isinstance(ctx, _CompileStateSmugglingCtx): # only present if debugging is enabled |
| 628 |
template_obj._python_source_temp_path = ctx.python_source_temp_path # facilitate deletion of the temp file when template_obj is deleted |
| 629 |
|
| 630 |
return template_obj |
| 631 |
|
| 632 |
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool: |
| 633 |
# deprecated: description="remove relaxed template sandbox mode support" core_version="2.23" |
| 634 |
if _TemplateConfig.sandbox_mode == _SandboxMode.ALLOW_UNSAFE_ATTRIBUTES: |
| 635 |
return True |
| 636 |
|
| 637 |
if (type_or_tuple := self._allowed_unsafe_attributes.get(attr)) and isinstance(obj, type_or_tuple): |
| 638 |
return True |
| 639 |
|
| 640 |
return super().is_safe_attribute(obj, attr, value) |
| 641 |
|
| 642 |
@property |
| 643 |
def lexer(self) -> AnsibleLexer: |
| 644 |
"""Return/cache an AnsibleLexer with settings from the current AnsibleEnvironment""" |
| 645 |
# DTFIX-FUTURE: optimization - we should pre-generate the default cached lexer before forking, not leave it to chance (e.g. simple playbooks) |
| 646 |
key = tuple(getattr(self, name) for name in _TEMPLATE_OVERRIDE_FIELD_NAMES) |
| 647 |
|
| 648 |
lex = self._lexer_cache.get(key) |
| 649 |
|
| 650 |
if lex is None: |
| 651 |
self._lexer_cache[key] = lex = AnsibleLexer(self) |
| 652 |
|
| 653 |
return lex |
| 654 |
|
| 655 |
def call_filter( |
| 656 |
self, |
| 657 |
name: str, |
| 658 |
value: t.Any, |
| 659 |
args: c.Sequence[t.Any] | None = None, |
| 660 |
kwargs: c.Mapping[str, t.Any] | None = None, |
| 661 |
context: Context | None = None, |
| 662 |
eval_ctx: EvalContext | None = None, |
| 663 |
) -> t.Any: |
| 664 |
""" |
| 665 |
Ensure that filters directly invoked by plugins will see non-templating lazy containers. |
| 666 |
Without this, `_wrap_filter` will wrap `args` and `kwargs` in templating lazy containers. |
| 667 |
This provides consistency with plugin output handling by preventing auto-templating of trusted templates passed in native containers. |
| 668 |
""" |
| 669 |
# DTFIX-FUTURE: need better logic to handle non-list/non-dict inputs for args/kwargs |
| 670 |
args = _AnsibleLazyTemplateMixin._try_create(list(args or []), LazyOptions.SKIP_TEMPLATES) |
| 671 |
kwargs = _AnsibleLazyTemplateMixin._try_create(kwargs, LazyOptions.SKIP_TEMPLATES) |
| 672 |
|
| 673 |
return super().call_filter(name, value, args, kwargs, context, eval_ctx) |
| 674 |
|
| 675 |
def call_test( |
| 676 |
self, |
| 677 |
name: str, |
| 678 |
value: t.Any, |
| 679 |
args: c.Sequence[t.Any] | None = None, |
| 680 |
kwargs: c.Mapping[str, t.Any] | None = None, |
| 681 |
context: Context | None = None, |
| 682 |
eval_ctx: EvalContext | None = None, |
| 683 |
) -> t.Any: |
| 684 |
""" |
| 685 |
Ensure that tests directly invoked by plugins will see non-templating lazy containers. |
| 686 |
Without this, `_wrap_test` will wrap `args` and `kwargs` in templating lazy containers. |
| 687 |
This provides consistency with plugin output handling by preventing auto-templating of trusted templates passed in native containers. |
| 688 |
""" |
| 689 |
# DTFIX-FUTURE: need better logic to handle non-list/non-dict inputs for args/kwargs |
| 690 |
args = _AnsibleLazyTemplateMixin._try_create(list(args or []), LazyOptions.SKIP_TEMPLATES) |
| 691 |
kwargs = _AnsibleLazyTemplateMixin._try_create(kwargs, LazyOptions.SKIP_TEMPLATES) |
| 692 |
|
| 693 |
return super().call_test(name, value, args, kwargs, context, eval_ctx) |
| 694 |
|
| 695 |
def compile_expression(self, source: str, *args, **kwargs) -> TemplateExpression: |
| 696 |
# compile_expression parses and passes the tree to from_string; for debug support, activate the context here to capture the intermediate results |
| 697 |
with _CompileStateSmugglingCtx.when(self._debuggable_template_source) as ctx: |
| 698 |
if isinstance(ctx, _CompileStateSmugglingCtx): # only present if debugging is enabled |
| 699 |
ctx.template_source = source |
| 700 |
|
| 701 |
return super().compile_expression(source, *args, **kwargs) |
| 702 |
|
| 703 |
def from_string(self, source: str | jinja2.nodes.Template, *args, **kwargs) -> AnsibleTemplate: |
| 704 |
# if debugging is enabled, use existing context when present (e.g., from compile_expression) |
| 705 |
current_ctx = _CompileStateSmugglingCtx.current(optional=True) if self._debuggable_template_source else None |
| 706 |
|
| 707 |
with _CompileStateSmugglingCtx.when(self._debuggable_template_source and not current_ctx) as new_ctx: |
| 708 |
template_obj = t.cast(AnsibleTemplate, super().from_string(source, *args, **kwargs)) |
| 709 |
|
| 710 |
if isinstance(ctx := current_ctx or new_ctx, _CompileStateSmugglingCtx): # only present if debugging is enabled |
| 711 |
template_obj._python_source_temp_path = ctx.python_source_temp_path # facilitate deletion of the temp file when template_obj is deleted |
| 712 |
|
| 713 |
return template_obj |
| 714 |
|
| 715 |
def _parse(self, source: str, *args, **kwargs) -> jinja2.nodes.Template: |
| 716 |
if csc := _CompileStateSmugglingCtx.current(optional=True): |
| 717 |
csc.template_source = source |
| 718 |
|
| 719 |
return super()._parse(source, *args, **kwargs) |
| 720 |
|
| 721 |
def _compile(self, source: str, filename: str) -> types.CodeType: |
| 722 |
if csc := _CompileStateSmugglingCtx.current(optional=True): |
| 723 |
origin = Origin.get_tag(csc.template_source) or Origin.UNKNOWN |
| 724 |
|
| 725 |
source = '\n'.join( |
| 726 |
( |
| 727 |
"import sys; breakpoint() if type(sys.breakpointhook) is not type(breakpoint) else None", |
| 728 |
f"# original template source from {str(origin)!r}: ", |
| 729 |
'\n'.join(f'# {line}' for line in (csc.template_source or '').splitlines()), |
| 730 |
source, |
| 731 |
) |
| 732 |
) |
| 733 |
|
| 734 |
source_temp_dir = self._debuggable_template_source_path |
| 735 |
source_temp_dir.mkdir(parents=True, exist_ok=True) |
| 736 |
|
| 737 |
with tempfile.NamedTemporaryFile(dir=source_temp_dir, mode='w', suffix='.py', prefix='j2_src_', delete=False) as source_file: |
| 738 |
filename = source_file.name |
| 739 |
|
| 740 |
source_file.write(source) |
| 741 |
source_file.flush() |
| 742 |
|
| 743 |
csc.python_source = source |
| 744 |
csc.python_source_temp_path = pathlib.Path(filename) |
| 745 |
|
| 746 |
res = super()._compile(source, filename) |
| 747 |
|
| 748 |
return res |
| 749 |
|
| 750 |
@staticmethod |
| 751 |
def concat(nodes: t.Iterable[t.Any]) -> t.Any: # type: ignore[override] |
| 752 |
node_list = list(_flatten_nodes(nodes)) |
| 753 |
|
| 754 |
if not node_list: |
| 755 |
return None |
| 756 |
|
| 757 |
# this code is complemented by our tweaked CodeGenerator _output_const_repr that ensures that literal constants |
| 758 |
# in templates aren't double-repr'd in the generated code |
| 759 |
if len(node_list) == 1: |
| 760 |
return node_list[0] |
| 761 |
|
| 762 |
# In order to ensure that all markers are tripped, do a recursive finalize before we repr (otherwise we can end up |
| 763 |
# repr'ing a Marker). This requires two passes, but avoids the need for a parallel reimplementation of all repr methods. |
| 764 |
try: |
| 765 |
node_list = _finalize_template_result(node_list, FinalizeMode.CONCAT) |
| 766 |
except MarkerError as ex: |
| 767 |
return ex.source # return the first Marker encountered |
| 768 |
|
| 769 |
return ''.join([to_text(v) for v in node_list]) |
| 770 |
|
| 771 |
@staticmethod |
| 772 |
def _access_const(const_template: t.LiteralString) -> t.Any: |
| 773 |
""" |
| 774 |
Called during template rendering on template-looking string constants embedded in the template. |
| 775 |
It provides the following functionality: |
| 776 |
* Propagates origin from the containing template. |
| 777 |
* For backward compatibility when embedded templates are enabled: |
| 778 |
* Conditionals - Renders embedded template constants and accesses the result. Warns on each constant immediately. |
| 779 |
* Non-conditionals - Tags constants for deferred rendering of templates in lookup terms. Warns on each constant during lookup invocation. |
| 780 |
""" |
| 781 |
ctx = TemplateContext.current() |
| 782 |
|
| 783 |
if (tv := ctx.template_value) and (origin := Origin.get_tag(tv)): |
| 784 |
const_template = origin.tag(const_template) |
| 785 |
|
| 786 |
if ctx._render_jinja_const_template: |
| 787 |
_jinja_const_template_warning(const_template, is_conditional=True) |
| 788 |
|
| 789 |
result = ctx.templar.template(TrustedAsTemplate().tag(const_template)) |
| 790 |
AnsibleAccessContext.current().access(result) |
| 791 |
else: |
| 792 |
# warnings will be issued when lookup terms processing occurs, to avoid false positives |
| 793 |
result = _JinjaConstTemplate().tag(const_template) |
| 794 |
|
| 795 |
return result |
| 796 |
|
| 797 |
def getitem(self, obj: t.Any, argument: t.Any) -> t.Any: |
| 798 |
try: |
| 799 |
value = super().getitem(obj, argument) |
| 800 |
except _attribute_unavailable.AttributeUnavailableError as ex: |
| 801 |
value = self.undefined(obj=obj, name=str(argument), hint=_error_utils.format_exception_message(ex)) |
| 802 |
|
| 803 |
AnsibleAccessContext.current().access(value) |
| 804 |
|
| 805 |
return value |
| 806 |
|
| 807 |
def getattr(self, obj: t.Any, attribute: str) -> t.Any: |
| 808 |
""" |
| 809 |
Get `attribute` from the attributes of `obj`, falling back to items in `obj`. |
| 810 |
If no item was found, return a sandbox-specific `UndefinedMarker` if `attribute` is protected by the sandbox, |
| 811 |
otherwise return a normal `UndefinedMarker` instance. |
| 812 |
This differs from the built-in Jinja behavior which will not fall back to items if `attribute` is protected by the sandbox. |
| 813 |
""" |
| 814 |
# example template that uses this: "{{ some.thing }}" -- obj is the "some" dict, attribute is "thing" |
| 815 |
|
| 816 |
is_safe = True |
| 817 |
|
| 818 |
try: |
| 819 |
value = getattr(obj, attribute) |
| 820 |
except _attribute_unavailable.AttributeUnavailableError as ex: |
| 821 |
value = self.undefined(obj=obj, name=attribute, hint=_error_utils.format_exception_message(ex)) |
| 822 |
except AttributeError: |
| 823 |
value = _sentinel |
| 824 |
else: |
| 825 |
if not (is_safe := self.is_safe_attribute(obj, attribute, value)): |
| 826 |
value = _sentinel |
| 827 |
|
| 828 |
if value is _sentinel: |
| 829 |
try: |
| 830 |
value = obj[attribute] |
| 831 |
except (TypeError, LookupError): |
| 832 |
value = self.undefined(obj=obj, name=attribute) if is_safe else self.unsafe_undefined(obj, attribute) |
| 833 |
|
| 834 |
AnsibleAccessContext.current().access(value) |
| 835 |
|
| 836 |
return value |
| 837 |
|
| 838 |
def call( |
| 839 |
self, |
| 840 |
__context: Context, |
| 841 |
__obj: t.Any, |
| 842 |
*args: t.Any, |
| 843 |
**kwargs: t.Any, |
| 844 |
) -> t.Any: |
| 845 |
try: |
| 846 |
if _DirectCall.is_marked(__obj): |
| 847 |
# Both `_lookup` and `_query` handle arg proxying and `Marker` args internally. |
| 848 |
# Performing either before calling them will interfere with that processing. |
| 849 |
return super().call(__context, __obj, *args, **kwargs) |
| 850 |
|
| 851 |
# Jinja's generated macro code handles Markers, so preemptive raise on Marker args and lazy retrieval should be disabled for the macro invocation. |
| 852 |
is_macro = isinstance(__obj, Macro) |
| 853 |
|
| 854 |
if not is_macro and (first_marker := get_first_marker_arg(args, kwargs)) is not None: |
| 855 |
return first_marker |
| 856 |
|
| 857 |
with JinjaCallContext(accept_lazy_markers=is_macro): |
| 858 |
call_res = super().call(__context, __obj, *lazify_container_args(args), **lazify_container_kwargs(kwargs)) |
| 859 |
|
| 860 |
if __obj is range: |
| 861 |
# Preserve the ability to do `range(1000000000) | random` by not converting range objects to lists. |
| 862 |
# Historically, range objects were only converted on Jinja finalize and filter outputs, so they've always been floating around in templating |
| 863 |
# code and visible to user plugins. |
| 864 |
return call_res |
| 865 |
|
| 866 |
return _wrap_plugin_output(call_res) |
| 867 |
|
| 868 |
except MarkerError as ex: |
| 869 |
return ex.source |
| 870 |
except Exception as ex: |
| 871 |
return CapturedExceptionMarker(ex) |
| 872 |
|
| 873 |
|
| 874 |
AnsibleTemplate.environment_class = AnsibleEnvironment |
| 875 |
|
| 876 |
_DEFAULT_UNDEF = UndefinedMarker("Mandatory variable has not been overridden", _no_template_source=True) |
| 877 |
|
| 878 |
_sentinel: t.Final[object] = object() |
| 879 |
|
| 880 |
|
| 881 |
@_DirectCall.mark |
| 882 |
def _undef(hint: str | None = None) -> UndefinedMarker: |
| 883 |
"""Jinja2 global function (undef) for creating getting a `UndefinedMarker` instance, optionally with a custom hint.""" |
| 884 |
validate_arg_type('hint', hint, (str, type(None))) |
| 885 |
|
| 886 |
if not hint: |
| 887 |
return _DEFAULT_UNDEF |
| 888 |
|
| 889 |
return UndefinedMarker(hint) |
| 890 |
|
| 891 |
|
| 892 |
def _flatten_nodes(nodes: t.Iterable[t.Any]) -> t.Iterable[t.Any]: |
| 893 |
""" |
| 894 |
Yield nodes from a potentially recursive iterable of nodes. |
| 895 |
The recursion is required to expand template imports (TemplateModule). |
| 896 |
Any exception raised while consuming a template node will be yielded as a Marker for that node. |
| 897 |
""" |
| 898 |
iterator = iter(nodes) |
| 899 |
|
| 900 |
while True: |
| 901 |
try: |
| 902 |
node = next(iterator) |
| 903 |
except StopIteration: |
| 904 |
break |
| 905 |
except Exception as ex: |
| 906 |
yield defer_template_error(ex, TemplateContext.current().template_value, is_expression=False) |
| 907 |
# DTFIX-FUTURE: We should be able to determine if truncation occurred by having the code generator smuggle out the number of expected nodes. |
| 908 |
yield TruncationMarker() |
| 909 |
else: |
| 910 |
if type(node) is TemplateModule: # pylint: disable=unidiomatic-typecheck |
| 911 |
yield from _flatten_nodes(node._body_stream) |
| 912 |
elif node is None: |
| 913 |
continue # avoid yielding `None`-valued nodes to avoid literal "None" in stringified template results |
| 914 |
else: |
| 915 |
yield node |
| 916 |
|
| 917 |
|
| 918 |
def _flatten_and_lazify_vars(mapping: c.Mapping) -> t.Iterable[c.Mapping]: |
| 919 |
"""Prevent deeply-nested Jinja vars ChainMaps from being created by nested contexts and ensure that all top-level containers support lazy templating.""" |
| 920 |
mapping_type = type(mapping) |
| 921 |
if mapping_type is ChainMap: |
| 922 |
# noinspection PyUnresolvedReferences |
| 923 |
for m in mapping.maps: |
| 924 |
yield from _flatten_and_lazify_vars(m) |
| 925 |
elif mapping_type is _AnsibleLazyTemplateDict: |
| 926 |
yield mapping |
| 927 |
elif mapping_type in (dict, _AnsibleTaggedDict): |
| 928 |
# don't propagate empty dictionary layers |
| 929 |
if mapping: |
| 930 |
yield _AnsibleLazyTemplateMixin._try_create(mapping) |
| 931 |
else: |
| 932 |
raise NotImplementedError(f"unsupported mapping type in Jinja vars: {mapping_type}") |
| 933 |
|
| 934 |
|
| 935 |
def _new_context( |
| 936 |
*, |
| 937 |
environment: Environment, |
| 938 |
template_name: str | None, |
| 939 |
blocks: dict[str, t.Callable[[Context], c.Iterator[str]]], |
| 940 |
shared: bool = False, |
| 941 |
jinja_locals: c.Mapping[str, t.Any] | None = None, |
| 942 |
jinja_vars: c.Mapping[str, t.Any] | None = None, |
| 943 |
jinja_globals: c.MutableMapping[str, t.Any] | None = None, |
| 944 |
) -> Context: |
| 945 |
"""Override Jinja's context vars setup to use ChainMaps and containers that support lazy templating.""" |
| 946 |
layers = [] |
| 947 |
|
| 948 |
if jinja_locals: |
| 949 |
# Omit values set to Jinja's internal `missing` sentinel; they are locals that have not yet been |
| 950 |
# initialized in the current context, and should not be exposed to child contexts. e.g.: {% import 'a' as b with context %}. |
| 951 |
# The `b` local will be `missing` in the `a` context and should not be propagated as a local to the child context we're creating. |
| 952 |
layers.append(_AnsibleLazyTemplateMixin._try_create({k: v for k, v in jinja_locals.items() if v is not missing})) |
| 953 |
|
| 954 |
if jinja_vars: |
| 955 |
layers.extend(_flatten_and_lazify_vars(jinja_vars)) |
| 956 |
|
| 957 |
if jinja_globals and not shared: |
| 958 |
# Even though we don't currently support templating globals, it's easier to ensure that everything is template-able rather than trying to |
| 959 |
# pick apart the ChainMaps to enforce non-template-able globals, or to risk things that *should* be template-able not being lazified. |
| 960 |
layers.extend(_flatten_and_lazify_vars(jinja_globals)) |
| 961 |
|
| 962 |
if not layers: |
| 963 |
# ensure we have at least one layer (which should be lazy), since _flatten_and_lazify_vars eliminates most empty layers |
| 964 |
layers.append(_AnsibleLazyTemplateMixin._try_create({})) |
| 965 |
|
| 966 |
# only return a ChainMap if we're combining layers, or we have none |
| 967 |
parent = layers[0] if len(layers) == 1 else ChainMap(*layers) |
| 968 |
|
| 969 |
# the `parent` cast is only to satisfy Jinja's overly-strict type hint |
| 970 |
return environment.context_class(environment, t.cast(dict, parent), template_name, blocks, globals=jinja_globals) |
| 971 |
|
| 972 |
|
| 973 |
def is_possibly_template(value: str, overrides: TemplateOverrides = TemplateOverrides.DEFAULT): |
| 974 |
""" |
| 975 |
A lightweight check to determine if the given string looks like it contains a template, even if that template is invalid. |
| 976 |
Returns `True` if the given string starts with a Jinja overrides header or if it contains template start strings. |
| 977 |
""" |
| 978 |
return value.startswith(JINJA2_OVERRIDE) or overrides._contains_start_string(value) |
| 979 |
|
| 980 |
|
| 981 |
def is_possibly_all_template(value: str, overrides: TemplateOverrides = TemplateOverrides.DEFAULT): |
| 982 |
""" |
| 983 |
A lightweight check to determine if the given string looks like it contains *only* a template, even if that template is invalid. |
| 984 |
Returns `True` if the given string starts with a Jinja overrides header or if it starts and ends with Jinja template delimiters. |
| 985 |
""" |
| 986 |
return value.startswith(JINJA2_OVERRIDE) or overrides._starts_and_ends_with_jinja_delimiters(value) |
| 987 |
|
| 988 |
|
| 989 |
class FinalizeMode(enum.Enum): |
| 990 |
TOP_LEVEL = enum.auto() |
| 991 |
CONCAT = enum.auto() |
| 992 |
|
| 993 |
|
| 994 |
_FINALIZE_FAST_PATH_EXACT_MAPPING_TYPES = frozenset( |
| 995 |
( |
| 996 |
dict, |
| 997 |
_AnsibleTaggedDict, |
| 998 |
_AnsibleLazyTemplateDict, |
| 999 |
HostVars, |
| 1000 |
HostVarsVars, |
| 1001 |
) |
| 1002 |
) |
| 1003 |
"""Fast-path exact mapping types for finalization. These types bypass diagnostic warnings for type conversion.""" |
| 1004 |
|
| 1005 |
_FINALIZE_FAST_PATH_EXACT_ITERABLE_TYPES = frozenset( |
| 1006 |
( |
| 1007 |
list, |
| 1008 |
_AnsibleTaggedList, |
| 1009 |
_AnsibleLazyTemplateList, |
| 1010 |
tuple, |
| 1011 |
_AnsibleTaggedTuple, |
| 1012 |
_AnsibleLazyAccessTuple, |
| 1013 |
) |
| 1014 |
) |
| 1015 |
"""Fast-path exact iterable types for finalization. These types bypass diagnostic warnings for type conversion.""" |
| 1016 |
|
| 1017 |
_FINALIZE_DISALLOWED_EXACT_TYPES = frozenset((range,)) |
| 1018 |
"""Exact types that cannot be finalized.""" |
| 1019 |
|
| 1020 |
# Jinja passes these into filters/tests via @pass_environment |
| 1021 |
register_known_types( |
| 1022 |
AnsibleContext, |
| 1023 |
AnsibleEnvironment, |
| 1024 |
EvalContext, |
| 1025 |
) |
| 1026 |
|
| 1027 |
|
| 1028 |
def _finalize_dict(o: t.Any, mode: FinalizeMode) -> t.Iterator[tuple[t.Any, t.Any]]: |
| 1029 |
for k, v in o.items(): |
| 1030 |
if v is not Omit: |
| 1031 |
yield _finalize_template_result(k, mode), _finalize_template_result(v, mode) |
| 1032 |
|
| 1033 |
|
| 1034 |
def _finalize_list(o: t.Any, mode: FinalizeMode) -> t.Iterator[t.Any]: |
| 1035 |
for v in o: |
| 1036 |
if v is not Omit: |
| 1037 |
yield _finalize_template_result(v, mode) |
| 1038 |
|
| 1039 |
|
| 1040 |
def _maybe_finalize_scalar(o: t.Any) -> t.Any: |
| 1041 |
# DTFIX5: this should check all supported scalar subclasses, not just JSON ones (also, does the JSON serializer handle these cases?) |
| 1042 |
for target_type in _json_subclassable_scalar_types: |
| 1043 |
if not isinstance(o, target_type): |
| 1044 |
continue |
| 1045 |
|
| 1046 |
match _TemplateConfig.unknown_type_conversion_handler.action: |
| 1047 |
# we don't want to show the object value, and it can't be Origin-tagged; send the current template value for best effort |
| 1048 |
case ErrorAction.WARNING: |
| 1049 |
display.warning( |
| 1050 |
msg=f'Type {native_type_name(o)!r} is unsupported in variable storage, converting to {native_type_name(target_type)!r}.', |
| 1051 |
obj=TemplateContext.current(optional=True).template_value, |
| 1052 |
) |
| 1053 |
case ErrorAction.ERROR: |
| 1054 |
raise AnsibleVariableTypeError.from_value(obj=TemplateContext.current(optional=True).template_value) |
| 1055 |
|
| 1056 |
return target_type(o) |
| 1057 |
|
| 1058 |
return None |
| 1059 |
|
| 1060 |
|
| 1061 |
def _finalize_fallback_collection( |
| 1062 |
o: t.Any, |
| 1063 |
mode: FinalizeMode, |
| 1064 |
finalizer: t.Callable[[t.Any, FinalizeMode], t.Iterator], |
| 1065 |
target_type: type[list | dict], |
| 1066 |
) -> t.Collection[t.Any]: |
| 1067 |
match _TemplateConfig.unknown_type_conversion_handler.action: |
| 1068 |
# we don't want to show the object value, and it can't be Origin-tagged; send the current template value for best effort |
| 1069 |
case ErrorAction.WARNING: |
| 1070 |
display.warning( |
| 1071 |
msg=f'Type {native_type_name(o)!r} is unsupported in variable storage, converting to {native_type_name(target_type)!r}.', |
| 1072 |
obj=TemplateContext.current(optional=True).template_value, |
| 1073 |
) |
| 1074 |
case ErrorAction.ERROR: |
| 1075 |
raise AnsibleVariableTypeError.from_value(obj=TemplateContext.current(optional=True).template_value) |
| 1076 |
|
| 1077 |
return _finalize_collection(o, mode, finalizer, target_type) |
| 1078 |
|
| 1079 |
|
| 1080 |
def _finalize_collection( |
| 1081 |
o: t.Any, |
| 1082 |
mode: FinalizeMode, |
| 1083 |
finalizer: t.Callable[[t.Any, FinalizeMode], t.Iterator], |
| 1084 |
target_type: type[list | dict], |
| 1085 |
) -> t.Collection[t.Any]: |
| 1086 |
return AnsibleTagHelper.tag(finalizer(o, mode), AnsibleTagHelper.tags(o), value_type=target_type) |
| 1087 |
|
| 1088 |
|
| 1089 |
def _finalize_template_result(o: t.Any, mode: FinalizeMode) -> t.Any: |
| 1090 |
"""Recurse the template result, rendering any encountered templates, converting containers to non-lazy versions.""" |
| 1091 |
# DTFIX5: add tests to ensure this method doesn't drift from allowed types |
| 1092 |
o_type = type(o) |
| 1093 |
|
| 1094 |
# DTFIX-FUTURE: provide an optional way to check for trusted templates leaking out of templating (injected, but not passed through templar.template) |
| 1095 |
|
| 1096 |
if o_type is _AnsibleTaggedStr: |
| 1097 |
return _JinjaConstTemplate.untag(o) # prevent _JinjaConstTemplate from leaking into finalized results |
| 1098 |
|
| 1099 |
if o_type in PASS_THROUGH_SCALAR_VAR_TYPES: |
| 1100 |
return o |
| 1101 |
|
| 1102 |
if o_type in _FINALIZE_FAST_PATH_EXACT_MAPPING_TYPES: # silently convert known mapping types to dict |
| 1103 |
return _finalize_collection(o, mode, _finalize_dict, dict) |
| 1104 |
|
| 1105 |
if o_type in _FINALIZE_FAST_PATH_EXACT_ITERABLE_TYPES: # silently convert known sequence types to list |
| 1106 |
return _finalize_collection(o, mode, _finalize_list, list) |
| 1107 |
|
| 1108 |
if o_type in Marker._concrete_subclasses: # this early return assumes handle_marker follows our variable type rules |
| 1109 |
return TemplateContext.current().templar.marker_behavior.handle_marker(o) |
| 1110 |
|
| 1111 |
if mode is not FinalizeMode.TOP_LEVEL: # unsupported type (do not raise) |
| 1112 |
return o |
| 1113 |
|
| 1114 |
if o_type in _FINALIZE_DISALLOWED_EXACT_TYPES: # early abort for disallowed types that would otherwise be handled below |
| 1115 |
raise AnsibleVariableTypeError.from_value(obj=o) |
| 1116 |
|
| 1117 |
if _internal.is_intermediate_mapping(o): # since isinstance checks are slower, this is separate from the exact type check above |
| 1118 |
return _finalize_fallback_collection(o, mode, _finalize_dict, dict) |
| 1119 |
|
| 1120 |
if _internal.is_intermediate_iterable(o): # since isinstance checks are slower, this is separate from the exact type check above |
| 1121 |
return _finalize_fallback_collection(o, mode, _finalize_list, list) |
| 1122 |
|
| 1123 |
if (result := _maybe_finalize_scalar(o)) is not None: |
| 1124 |
return result |
| 1125 |
|
| 1126 |
raise AnsibleVariableTypeError.from_value(obj=o) |