| 1 |
from __future__ import annotations as _annotations |
| 2 |
|
| 3 |
import contextlib as _contextlib |
| 4 |
import io as _io |
| 5 |
import os as _os |
| 6 |
import typing as _t |
| 7 |
|
| 8 |
from jinja2 import environment as _environment |
| 9 |
|
| 10 |
from ansible import _internal |
| 11 |
from ansible import errors as _errors |
| 12 |
from ansible._internal._datatag import _tags, _wrappers |
| 13 |
from ansible._internal._templating import _jinja_bits, _engine, _jinja_common, _template_vars |
| 14 |
|
| 15 |
from ansible.module_utils import datatag as _module_utils_datatag |
| 16 |
from ansible.utils.display import Display as _Display |
| 17 |
|
| 18 |
if _t.TYPE_CHECKING: # pragma: nocover |
| 19 |
import collections as _collections |
| 20 |
|
| 21 |
from ansible.parsing import dataloader as _dataloader |
| 22 |
|
| 23 |
_VariableContainer = dict[str, _t.Any] | _collections.ChainMap[str, _t.Any] |
| 24 |
|
| 25 |
|
| 26 |
_display: _t.Final[_Display] = _Display() |
| 27 |
_UNSET = _t.cast(_t.Any, object()) |
| 28 |
_TRUSTABLE_TYPES = (str, _io.IOBase) |
| 29 |
|
| 30 |
AnsibleUndefined = _jinja_common.UndefinedMarker |
| 31 |
"""Backwards compatibility alias for UndefinedMarker.""" |
| 32 |
|
| 33 |
|
| 34 |
class Templar: |
| 35 |
"""Primary public API container for Ansible's template engine.""" |
| 36 |
|
| 37 |
def __init__( |
| 38 |
self, |
| 39 |
loader: _dataloader.DataLoader | None = None, |
| 40 |
variables: _VariableContainer | None = None, |
| 41 |
) -> None: |
| 42 |
self._engine = _engine.TemplateEngine(loader=loader, variables=variables) |
| 43 |
self._overrides = _jinja_bits.TemplateOverrides.DEFAULT |
| 44 |
|
| 45 |
@classmethod |
| 46 |
@_internal.experimental |
| 47 |
def _from_template_engine(cls, engine: _engine.TemplateEngine) -> _t.Self: |
| 48 |
""" |
| 49 |
EXPERIMENTAL: For internal use within ansible-core only. |
| 50 |
Create a `Templar` instance from the given `TemplateEngine` instance. |
| 51 |
""" |
| 52 |
templar = object.__new__(cls) |
| 53 |
templar._engine = engine.copy() |
| 54 |
templar._overrides = _jinja_bits.TemplateOverrides.DEFAULT |
| 55 |
|
| 56 |
return templar |
| 57 |
|
| 58 |
def resolve_variable_expression( |
| 59 |
self, |
| 60 |
expression: str, |
| 61 |
*, |
| 62 |
local_variables: dict[str, _t.Any] | None = None, |
| 63 |
) -> _t.Any: |
| 64 |
""" |
| 65 |
Resolve a potentially untrusted string variable expression consisting only of valid identifiers, integers, dots, and indexing containing these. |
| 66 |
Optional local variables may be provided, which can only be referenced directly by the given expression. |
| 67 |
Valid: x, x.y, x[y].z, x[1], 1, x[y.z] |
| 68 |
Error: 'x', x['y'], q('env') |
| 69 |
""" |
| 70 |
return self._engine.resolve_variable_expression(expression, local_variables=local_variables) |
| 71 |
|
| 72 |
def evaluate_expression( |
| 73 |
self, |
| 74 |
expression: str, |
| 75 |
*, |
| 76 |
local_variables: dict[str, _t.Any] | None = None, |
| 77 |
escape_backslashes: bool = True, |
| 78 |
) -> _t.Any: |
| 79 |
""" |
| 80 |
Evaluate a trusted string expression and return its result. |
| 81 |
Optional local variables may be provided, which can only be referenced directly by the given expression. |
| 82 |
""" |
| 83 |
return self._engine.evaluate_expression(expression, local_variables=local_variables, escape_backslashes=escape_backslashes) |
| 84 |
|
| 85 |
def evaluate_conditional(self, conditional: str | bool) -> bool: |
| 86 |
""" |
| 87 |
Evaluate a trusted string expression or boolean and return its boolean result. A non-boolean result will raise `AnsibleBrokenConditionalError`. |
| 88 |
The ALLOW_BROKEN_CONDITIONALS configuration option can temporarily relax this requirement, allowing truthy conditionals to succeed. |
| 89 |
The ALLOW_EMBEDDED_TEMPLATES configuration option can temporarily enable inline Jinja template delimiter support (e.g., {{ }}, {% %}). |
| 90 |
""" |
| 91 |
return self._engine.evaluate_conditional(conditional) |
| 92 |
|
| 93 |
@property |
| 94 |
def basedir(self) -> str: |
| 95 |
"""The basedir from DataLoader.""" |
| 96 |
# DTFIX-FUTURE: come up with a better way to handle this so it can be deprecated |
| 97 |
return self._engine.basedir |
| 98 |
|
| 99 |
@property |
| 100 |
def available_variables(self) -> _VariableContainer: |
| 101 |
"""Available variables this instance will use when templating.""" |
| 102 |
return self._engine.available_variables |
| 103 |
|
| 104 |
@available_variables.setter |
| 105 |
def available_variables(self, variables: _VariableContainer) -> None: |
| 106 |
self._engine.available_variables = variables |
| 107 |
|
| 108 |
@property |
| 109 |
def _available_variables(self) -> _VariableContainer: |
| 110 |
"""Deprecated. Use `available_variables` instead.""" |
| 111 |
# Commonly abused by numerous collection lookup plugins and the Ceph Ansible `config_template` action. |
| 112 |
_display.deprecated( |
| 113 |
msg='Direct access to the `_available_variables` internal attribute is deprecated.', |
| 114 |
help_text='Use `available_variables` instead.', |
| 115 |
version='2.23', |
| 116 |
) |
| 117 |
|
| 118 |
return self.available_variables |
| 119 |
|
| 120 |
@property |
| 121 |
def _loader(self) -> _dataloader.DataLoader: |
| 122 |
"""Deprecated. Use `copy_with_new_env` to create a new instance.""" |
| 123 |
# Abused by cloud.common, community.general and felixfontein.tools collections to create a new Templar instance. |
| 124 |
_display.deprecated( |
| 125 |
msg='Direct access to the `_loader` internal attribute is deprecated.', |
| 126 |
help_text='Use `copy_with_new_env` to create a new instance.', |
| 127 |
version='2.23', |
| 128 |
) |
| 129 |
|
| 130 |
return self._engine._loader |
| 131 |
|
| 132 |
@property |
| 133 |
def environment(self) -> _environment.Environment: |
| 134 |
"""Deprecated.""" |
| 135 |
_display.deprecated( |
| 136 |
msg='Direct access to the `environment` attribute is deprecated.', |
| 137 |
help_text='Consider using `copy_with_new_env` or passing `overrides` to `template`.', |
| 138 |
version='2.23', |
| 139 |
) |
| 140 |
|
| 141 |
return self._engine.environment |
| 142 |
|
| 143 |
def copy_with_new_env( |
| 144 |
self, |
| 145 |
*, |
| 146 |
searchpath: str | _os.PathLike | _t.Sequence[str | _os.PathLike] | None = None, |
| 147 |
available_variables: _VariableContainer | None = None, |
| 148 |
**context_overrides: _t.Any, |
| 149 |
) -> Templar: |
| 150 |
"""Return a new templar based on the current one with customizations applied.""" |
| 151 |
if context_overrides.pop('environment_class', _UNSET) is not _UNSET: |
| 152 |
_display.deprecated( |
| 153 |
msg="The `environment_class` argument is ignored.", |
| 154 |
version='2.23', |
| 155 |
) |
| 156 |
|
| 157 |
if context_overrides: |
| 158 |
_display.deprecated( |
| 159 |
msg='Passing Jinja environment overrides to `copy_with_new_env` is deprecated.', |
| 160 |
help_text='Pass Jinja environment overrides to individual `template` calls.', |
| 161 |
version='2.23', |
| 162 |
) |
| 163 |
|
| 164 |
templar = Templar( |
| 165 |
loader=self._engine._loader, |
| 166 |
variables=self._engine._variables if available_variables is None else available_variables, |
| 167 |
) |
| 168 |
|
| 169 |
# backward compatibility: filter out None values from overrides, even though it is a valid value for some of them |
| 170 |
templar._overrides = self._overrides.merge({key: value for key, value in context_overrides.items() if value is not None}) |
| 171 |
|
| 172 |
if searchpath is not None: |
| 173 |
templar._engine.environment.loader.searchpath = searchpath |
| 174 |
|
| 175 |
return templar |
| 176 |
|
| 177 |
@_contextlib.contextmanager |
| 178 |
def set_temporary_context( |
| 179 |
self, |
| 180 |
*, |
| 181 |
searchpath: str | _os.PathLike | _t.Sequence[str | _os.PathLike] | None = None, |
| 182 |
available_variables: _VariableContainer | None = None, |
| 183 |
**context_overrides: _t.Any, |
| 184 |
) -> _t.Generator[None, None, None]: |
| 185 |
"""Context manager used to set temporary templating context, without having to worry about resetting original values afterward.""" |
| 186 |
_display.deprecated( |
| 187 |
msg='The `set_temporary_context` method on `Templar` is deprecated.', |
| 188 |
help_text='Use the `copy_with_new_env` method on `Templar` instead.', |
| 189 |
version='2.23', |
| 190 |
) |
| 191 |
|
| 192 |
targets = dict( |
| 193 |
searchpath=self._engine.environment.loader, |
| 194 |
available_variables=self._engine, |
| 195 |
) |
| 196 |
|
| 197 |
target_args = dict( |
| 198 |
searchpath=searchpath, |
| 199 |
available_variables=available_variables, |
| 200 |
) |
| 201 |
|
| 202 |
original: dict[str, _t.Any] = {} |
| 203 |
previous_overrides = self._overrides |
| 204 |
|
| 205 |
try: |
| 206 |
for key, value in target_args.items(): |
| 207 |
if value is not None: |
| 208 |
target = targets[key] |
| 209 |
original[key] = getattr(target, key) |
| 210 |
setattr(target, key, value) |
| 211 |
|
| 212 |
# backward compatibility: filter out None values from overrides, even though it is a valid value for some of them |
| 213 |
self._overrides = self._overrides.merge({key: value for key, value in context_overrides.items() if value is not None}) |
| 214 |
|
| 215 |
yield |
| 216 |
finally: |
| 217 |
for key, value in original.items(): |
| 218 |
setattr(targets[key], key, value) |
| 219 |
|
| 220 |
self._overrides = previous_overrides |
| 221 |
|
| 222 |
# noinspection PyUnusedLocal |
| 223 |
def template( |
| 224 |
self, |
| 225 |
variable: _t.Any, |
| 226 |
convert_bare: bool = _UNSET, |
| 227 |
preserve_trailing_newlines: bool = True, |
| 228 |
escape_backslashes: bool = True, |
| 229 |
fail_on_undefined: bool = True, |
| 230 |
overrides: dict[str, _t.Any] | None = None, |
| 231 |
convert_data: bool = _UNSET, |
| 232 |
disable_lookups: bool = _UNSET, |
| 233 |
) -> _t.Any: |
| 234 |
"""Templates (possibly recursively) any given data as input.""" |
| 235 |
# DTFIX-FUTURE: offer a public version of TemplateOverrides to support an optional strongly typed `overrides` argument |
| 236 |
if convert_bare is not _UNSET: |
| 237 |
# Skipping a deferred deprecation due to minimal usage outside ansible-core. |
| 238 |
# Use `hasattr(templar, 'evaluate_expression')` to determine if `template` or `evaluate_expression` should be used. |
| 239 |
_display.deprecated( |
| 240 |
msg="Passing `convert_bare` to `template` is deprecated.", |
| 241 |
help_text="Use `evaluate_expression` instead.", |
| 242 |
version="2.23", |
| 243 |
) |
| 244 |
|
| 245 |
if convert_bare and isinstance(variable, str): |
| 246 |
contains_filters = "|" in variable |
| 247 |
first_part = variable.split("|")[0].split(".")[0].split("[")[0] |
| 248 |
convert_bare = (contains_filters or first_part in self.available_variables) and not self.is_possibly_template(variable, overrides) |
| 249 |
else: |
| 250 |
convert_bare = False |
| 251 |
else: |
| 252 |
convert_bare = False |
| 253 |
|
| 254 |
if fail_on_undefined is None: |
| 255 |
# The pre-2.19 config fallback is ignored for content portability. |
| 256 |
_display.deprecated( |
| 257 |
msg="Falling back to `True` for `fail_on_undefined`.", |
| 258 |
help_text="Use either `True` or `False` for `fail_on_undefined` when calling `template`.", |
| 259 |
version="2.23", |
| 260 |
) |
| 261 |
|
| 262 |
fail_on_undefined = True |
| 263 |
|
| 264 |
if convert_data is not _UNSET: |
| 265 |
# Skipping a deferred deprecation due to minimal usage outside ansible-core. |
| 266 |
# Use `hasattr(templar, 'evaluate_expression')` as a surrogate check to determine if `convert_data` is accepted. |
| 267 |
_display.deprecated( |
| 268 |
msg="Passing `convert_data` to `template` is deprecated.", |
| 269 |
version="2.23", |
| 270 |
) |
| 271 |
|
| 272 |
if disable_lookups is not _UNSET: |
| 273 |
# Skipping a deferred deprecation due to no known usage outside ansible-core. |
| 274 |
# Use `hasattr(templar, 'evaluate_expression')` as a surrogate check to determine if `disable_lookups` is accepted. |
| 275 |
_display.deprecated( |
| 276 |
msg="Passing `disable_lookups` to `template` is deprecated.", |
| 277 |
version="2.23", |
| 278 |
) |
| 279 |
|
| 280 |
try: |
| 281 |
if convert_bare: # pre-2.19 compat |
| 282 |
return self.evaluate_expression(variable, escape_backslashes=escape_backslashes) |
| 283 |
|
| 284 |
return self._engine.template( |
| 285 |
variable=variable, |
| 286 |
options=_engine.TemplateOptions( |
| 287 |
preserve_trailing_newlines=preserve_trailing_newlines, |
| 288 |
escape_backslashes=escape_backslashes, |
| 289 |
overrides=self._overrides.merge(overrides), |
| 290 |
), |
| 291 |
mode=_engine.TemplateMode.ALWAYS_FINALIZE, |
| 292 |
) |
| 293 |
except _errors.AnsibleUndefinedVariable: |
| 294 |
if not fail_on_undefined: |
| 295 |
return variable |
| 296 |
|
| 297 |
raise |
| 298 |
|
| 299 |
def is_template(self, data: _t.Any) -> bool: |
| 300 |
""" |
| 301 |
Evaluate the input data to determine if it contains a template, even if that template is invalid. Containers will be recursively searched. |
| 302 |
Objects subject to template-time transforms that do not yield a template are not considered templates by this method. |
| 303 |
Gating a conditional call to `template` with this method is redundant and inefficient -- request templating unconditionally instead. |
| 304 |
""" |
| 305 |
return self._engine.is_template(data, self._overrides) |
| 306 |
|
| 307 |
def is_possibly_template( |
| 308 |
self, |
| 309 |
data: _t.Any, |
| 310 |
overrides: dict[str, _t.Any] | None = None, |
| 311 |
) -> bool: |
| 312 |
""" |
| 313 |
A lightweight check to determine if the given value is a string that looks like it contains a template, even if that template is invalid. |
| 314 |
Returns `True` if the given value is a string that starts with a Jinja overrides header or if it contains template start strings. |
| 315 |
Gating a conditional call to `template` with this method is redundant and inefficient -- request templating unconditionally instead. |
| 316 |
""" |
| 317 |
return isinstance(data, str) and _jinja_bits.is_possibly_template(data, self._overrides.merge(overrides)) |
| 318 |
|
| 319 |
def do_template( |
| 320 |
self, |
| 321 |
data: _t.Any, |
| 322 |
preserve_trailing_newlines: bool = True, |
| 323 |
escape_backslashes: bool = True, |
| 324 |
fail_on_undefined: bool = True, |
| 325 |
overrides: dict[str, _t.Any] | None = None, |
| 326 |
disable_lookups: bool = _UNSET, |
| 327 |
convert_data: bool = _UNSET, |
| 328 |
) -> _t.Any: |
| 329 |
"""Deprecated. Use `template` instead.""" |
| 330 |
_display.deprecated( |
| 331 |
msg='The `do_template` method on `Templar` is deprecated.', |
| 332 |
help_text='Use the `template` method on `Templar` instead.', |
| 333 |
version='2.23', |
| 334 |
) |
| 335 |
|
| 336 |
if not isinstance(data, str): |
| 337 |
return data |
| 338 |
|
| 339 |
return self.template( |
| 340 |
variable=data, |
| 341 |
preserve_trailing_newlines=preserve_trailing_newlines, |
| 342 |
escape_backslashes=escape_backslashes, |
| 343 |
fail_on_undefined=fail_on_undefined, |
| 344 |
overrides=overrides, |
| 345 |
disable_lookups=disable_lookups, |
| 346 |
convert_data=convert_data, |
| 347 |
) |
| 348 |
|
| 349 |
|
| 350 |
def generate_ansible_template_vars( |
| 351 |
path: str, |
| 352 |
fullpath: str | None = None, |
| 353 |
dest_path: str | None = None, |
| 354 |
) -> dict[str, object]: |
| 355 |
""" |
| 356 |
Generate and return a dictionary with variable metadata about the template specified by `fullpath`. |
| 357 |
If `fullpath` is `None`, `path` will be used instead. |
| 358 |
""" |
| 359 |
# deprecated: description="deprecate `generate_ansible_template_vars`, collections should inline the necessary variables" core_version="2.23" |
| 360 |
return _template_vars.generate_ansible_template_vars(path=path, fullpath=fullpath, dest_path=dest_path, include_ansible_managed=True) |
| 361 |
|
| 362 |
|
| 363 |
def trust_as_template[T: str | _io.IOBase | _t.TextIO | _t.BinaryIO](value: T) -> T: |
| 364 |
""" |
| 365 |
Returns `value` tagged as trusted for templating. |
| 366 |
Raises a `TypeError` if `value` is not a supported type. |
| 367 |
""" |
| 368 |
if isinstance(value, str): |
| 369 |
return _tags.TrustedAsTemplate().tag(value) # type: ignore[return-value] |
| 370 |
|
| 371 |
if isinstance(value, _io.IOBase): # covers TextIO and BinaryIO at runtime, but type checking disagrees |
| 372 |
return _wrappers.TaggedStreamWrapper(value, _tags.TrustedAsTemplate()) |
| 373 |
|
| 374 |
raise TypeError(f"Trust cannot be applied to {_module_utils_datatag.native_type_name(value)}, only to 'str' or 'IOBase'.") |
| 375 |
|
| 376 |
|
| 377 |
def is_trusted_as_template(value: object) -> bool: |
| 378 |
""" |
| 379 |
Returns `True` if `value` is a `str` or `IOBase` marked as trusted for templating, otherwise returns `False`. |
| 380 |
Returns `False` for types which cannot be trusted for templating. |
| 381 |
Containers are not recursed and will always return `False`. |
| 382 |
This function should not be needed for production code, but may be useful in unit tests. |
| 383 |
""" |
| 384 |
return isinstance(value, _TRUSTABLE_TYPES) and _tags.TrustedAsTemplate.is_tagged_on(value) |
| 385 |
|
| 386 |
|
| 387 |
def accept_args_markers[T: _t.Callable](plugin: T) -> T: |
| 388 |
""" |
| 389 |
A decorator to mark a Jinja plugin as capable of handling `Marker` values for its top-level arguments. |
| 390 |
Non-decorated plugin invocation is skipped when a top-level argument is a `Marker`, with the first such value substituted as the plugin result. |
| 391 |
This ensures that only plugins which understand `Marker` instances for top-level arguments will encounter them. |
| 392 |
""" |
| 393 |
plugin.accept_args_markers = True |
| 394 |
|
| 395 |
return plugin |
| 396 |
|
| 397 |
|
| 398 |
def accept_lazy_markers[T: _t.Callable](plugin: T) -> T: |
| 399 |
""" |
| 400 |
A decorator to mark a Jinja plugin as capable of handling `Marker` values retrieved from lazy containers. |
| 401 |
Non-decorated plugins will trigger a `MarkerError` exception when attempting to retrieve a `Marker` from a lazy container. |
| 402 |
This ensures that only plugins which understand lazy retrieval of `Marker` instances will encounter them. |
| 403 |
""" |
| 404 |
plugin.accept_lazy_markers = True |
| 405 |
|
| 406 |
return plugin |
| 407 |
|
| 408 |
|
| 409 |
get_first_marker_arg = _jinja_common.get_first_marker_arg |