| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import copy |
| 7 |
import dataclasses |
| 8 |
import enum |
| 9 |
import typing as t |
| 10 |
import collections.abc as c |
| 11 |
import re |
| 12 |
|
| 13 |
from collections import ChainMap |
| 14 |
|
| 15 |
from ansible.errors import ( |
| 16 |
AnsibleError, |
| 17 |
AnsibleValueOmittedError, |
| 18 |
AnsibleUndefinedVariable, |
| 19 |
AnsibleTemplateSyntaxError, |
| 20 |
AnsibleBrokenConditionalError, |
| 21 |
AnsibleTemplateTransformLimitError, |
| 22 |
TemplateTrustCheckFailedError, |
| 23 |
) |
| 24 |
|
| 25 |
from ansible.module_utils._internal._datatag import AnsibleTaggedObject, NotTaggableError, AnsibleTagHelper |
| 26 |
from ansible._internal._errors._handler import Skippable |
| 27 |
from ansible._internal._datatag._tags import Origin, TrustedAsTemplate |
| 28 |
from ansible.utils.display import Display |
| 29 |
from ansible.utils.vars import validate_variable_name |
| 30 |
from ansible.parsing.dataloader import DataLoader |
| 31 |
|
| 32 |
from ._datatag import DeprecatedAccessAuditContext |
| 33 |
from ._jinja_bits import ( |
| 34 |
AnsibleTemplate, |
| 35 |
_TemplateCompileContext, |
| 36 |
TemplateOverrides, |
| 37 |
AnsibleEnvironment, |
| 38 |
defer_template_error, |
| 39 |
create_template_error, |
| 40 |
is_possibly_template, |
| 41 |
is_possibly_all_template, |
| 42 |
AnsibleTemplateExpression, |
| 43 |
_finalize_template_result, |
| 44 |
FinalizeMode, |
| 45 |
) |
| 46 |
from ._jinja_common import _TemplateConfig, MarkerError, ExceptionMarker, JinjaCallContext |
| 47 |
from ._lazy_containers import _AnsibleLazyTemplateMixin |
| 48 |
from ._marker_behaviors import MarkerBehavior, FAIL_ON_UNDEFINED |
| 49 |
from ._transform import _type_transform_mapping |
| 50 |
from ._utils import Omit, TemplateContext, IGNORE_SCALAR_VAR_TYPES, LazyOptions |
| 51 |
from ...module_utils.datatag import native_type_name |
| 52 |
|
| 53 |
_display = Display() |
| 54 |
|
| 55 |
|
| 56 |
_shared_empty_unmask_type_names: frozenset[str] = frozenset() |
| 57 |
|
| 58 |
TRANSFORM_CHAIN_LIMIT: int = 10 |
| 59 |
"""Arbitrary limit for chained transforms to prevent cycles; an exception will be raised if exceeded.""" |
| 60 |
|
| 61 |
|
| 62 |
class TemplateMode(enum.Enum): |
| 63 |
# DTFIX-FUTURE: this enum ideally wouldn't exist - revisit/rename before making public |
| 64 |
DEFAULT = enum.auto() |
| 65 |
STOP_ON_TEMPLATE = enum.auto() |
| 66 |
STOP_ON_CONTAINER = enum.auto() |
| 67 |
ALWAYS_FINALIZE = enum.auto() |
| 68 |
|
| 69 |
|
| 70 |
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True) |
| 71 |
class TemplateOptions: |
| 72 |
DEFAULT: t.ClassVar[t.Self] |
| 73 |
|
| 74 |
value_for_omit: object = Omit |
| 75 |
escape_backslashes: bool = True |
| 76 |
preserve_trailing_newlines: bool = True |
| 77 |
# DTFIX-FUTURE: these aren't really overrides anymore, rename the dataclass and this field |
| 78 |
# also mention in docstring this has no effect unless used to template a string |
| 79 |
overrides: TemplateOverrides = TemplateOverrides.DEFAULT |
| 80 |
|
| 81 |
|
| 82 |
TemplateOptions.DEFAULT = TemplateOptions() |
| 83 |
|
| 84 |
|
| 85 |
class TemplateEncountered(Exception): |
| 86 |
pass |
| 87 |
|
| 88 |
|
| 89 |
@t.final |
| 90 |
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True) |
| 91 |
class TemplateExpressionWrapper: |
| 92 |
"""Wrapper around a template expression which can be evaluated by the template engine.""" |
| 93 |
|
| 94 |
expression: str |
| 95 |
|
| 96 |
|
| 97 |
class TemplateEngine: |
| 98 |
""" |
| 99 |
The main class for templating, with the main entry-point of template(). |
| 100 |
""" |
| 101 |
|
| 102 |
_sentinel = object() |
| 103 |
|
| 104 |
def __init__( |
| 105 |
self, |
| 106 |
loader: DataLoader | None = None, |
| 107 |
variables: dict[str, t.Any] | ChainMap[str, t.Any] | None = None, |
| 108 |
variables_factory: t.Callable[[], dict[str, t.Any] | ChainMap[str, t.Any]] | None = None, |
| 109 |
marker_behavior: MarkerBehavior | None = None, |
| 110 |
): |
| 111 |
self._loader = loader |
| 112 |
self._variables = variables |
| 113 |
self._variables_factory = variables_factory |
| 114 |
self._environment: AnsibleEnvironment | None = None |
| 115 |
|
| 116 |
# inherit marker behavior from the active template context's templar unless otherwise specified |
| 117 |
if not marker_behavior: |
| 118 |
if template_ctx := TemplateContext.current(optional=True): |
| 119 |
marker_behavior = template_ctx.templar.marker_behavior |
| 120 |
else: |
| 121 |
marker_behavior = FAIL_ON_UNDEFINED |
| 122 |
|
| 123 |
self._marker_behavior = marker_behavior |
| 124 |
|
| 125 |
def copy(self) -> t.Self: |
| 126 |
new_engine = copy.copy(self) |
| 127 |
new_engine._environment = None |
| 128 |
|
| 129 |
return new_engine |
| 130 |
|
| 131 |
def extend(self, marker_behavior: MarkerBehavior | None = None, variables: dict[str, t.Any] | ChainMap[str, t.Any] | None = None) -> t.Self: |
| 132 |
new_templar = type(self)( |
| 133 |
loader=self._loader, |
| 134 |
# FUTURE: this should probably be a chainmap layer that proxies the base values to prevent aliased mutations of inner values being visible |
| 135 |
variables=variables or self._variables, |
| 136 |
variables_factory=self._variables_factory, |
| 137 |
marker_behavior=marker_behavior or self._marker_behavior, |
| 138 |
) |
| 139 |
|
| 140 |
if self._environment: |
| 141 |
new_templar._environment = self._environment |
| 142 |
|
| 143 |
return new_templar |
| 144 |
|
| 145 |
@property |
| 146 |
def marker_behavior(self) -> MarkerBehavior: |
| 147 |
return self._marker_behavior |
| 148 |
|
| 149 |
@property |
| 150 |
def basedir(self) -> str: |
| 151 |
"""The basedir from DataLoader.""" |
| 152 |
return self._loader.get_basedir() if self._loader else '.' |
| 153 |
|
| 154 |
@property |
| 155 |
def environment(self) -> AnsibleEnvironment: |
| 156 |
if not self._environment: |
| 157 |
self._environment = AnsibleEnvironment(ansible_basedir=self.basedir) |
| 158 |
|
| 159 |
return self._environment |
| 160 |
|
| 161 |
def _create_overlay(self, template: str, overrides: TemplateOverrides) -> tuple[str, AnsibleEnvironment]: |
| 162 |
try: |
| 163 |
template, overrides = overrides._extract_template_overrides(template) |
| 164 |
except Exception as ex: |
| 165 |
raise AnsibleTemplateSyntaxError("Syntax error in template.", obj=template) from ex |
| 166 |
|
| 167 |
env = self.environment |
| 168 |
|
| 169 |
if overrides is not TemplateOverrides.DEFAULT and (overlay_kwargs := overrides.overlay_kwargs()): |
| 170 |
env = t.cast(AnsibleEnvironment, env.overlay(**overlay_kwargs)) |
| 171 |
|
| 172 |
return template, env |
| 173 |
|
| 174 |
@staticmethod |
| 175 |
def _count_newlines_from_end(in_str): |
| 176 |
""" |
| 177 |
Counts the number of newlines at the end of a string. This is used during |
| 178 |
the jinja2 templating to ensure the count matches the input, since some newlines |
| 179 |
may be thrown away during the templating. |
| 180 |
""" |
| 181 |
|
| 182 |
i = len(in_str) |
| 183 |
j = i - 1 |
| 184 |
|
| 185 |
try: |
| 186 |
while in_str[j] == '\n': |
| 187 |
j -= 1 |
| 188 |
except IndexError: |
| 189 |
# Uncommon cases: zero length string and string containing only newlines |
| 190 |
return i |
| 191 |
|
| 192 |
return i - 1 - j |
| 193 |
|
| 194 |
@property |
| 195 |
def available_variables(self) -> dict[str, t.Any] | ChainMap[str, t.Any]: |
| 196 |
"""Available variables this instance will use when templating.""" |
| 197 |
# DTFIX3: ensure that we're always accessing this as a shallow container-level snapshot, and eliminate uses of anything |
| 198 |
# that directly mutates this value. _new_context may resolve this for us? |
| 199 |
if self._variables is None: |
| 200 |
self._variables = self._variables_factory() if self._variables_factory else {} |
| 201 |
|
| 202 |
return self._variables |
| 203 |
|
| 204 |
@available_variables.setter |
| 205 |
def available_variables(self, variables: dict[str, t.Any] | ChainMap[str, t.Any]) -> None: |
| 206 |
self._variables = variables |
| 207 |
|
| 208 |
def resolve_variable_expression( |
| 209 |
self, |
| 210 |
expression: str, |
| 211 |
*, |
| 212 |
local_variables: dict[str, t.Any] | None = None, |
| 213 |
) -> t.Any: |
| 214 |
""" |
| 215 |
Resolve a potentially untrusted string variable expression consisting only of valid identifiers, integers, dots, and indexing containing these. |
| 216 |
Optional local variables may be provided, which can only be referenced directly by the given expression. |
| 217 |
Valid: x, x.y, x[y].z, x[1], 1, x[y.z] |
| 218 |
Error: 'x', x['y'], q('env') |
| 219 |
""" |
| 220 |
components = re.split(r'[.\[\]]', expression) |
| 221 |
|
| 222 |
try: |
| 223 |
for component in components: |
| 224 |
if re.fullmatch('[0-9]*', component): |
| 225 |
continue # allow empty strings and integers |
| 226 |
|
| 227 |
validate_variable_name(component) |
| 228 |
except Exception as ex: |
| 229 |
raise AnsibleError(f'Invalid variable expression: {expression}', obj=expression) from ex |
| 230 |
|
| 231 |
return self.evaluate_expression(TrustedAsTemplate().tag(expression), local_variables=local_variables) |
| 232 |
|
| 233 |
@staticmethod |
| 234 |
def variable_name_as_template(name: str) -> str: |
| 235 |
"""Return a trusted template string that will resolve the provided variable name. Raises an error if `name` is not a valid identifier.""" |
| 236 |
validate_variable_name(name) |
| 237 |
return AnsibleTagHelper.tag('{{' + name + '}}', (AnsibleTagHelper.tags(name) | {TrustedAsTemplate()})) |
| 238 |
|
| 239 |
def transform(self, variable: t.Any) -> t.Any: |
| 240 |
"""Recursively apply transformations to the given value and return the result.""" |
| 241 |
return self.template(variable, mode=TemplateMode.ALWAYS_FINALIZE, lazy_options=LazyOptions.SKIP_TEMPLATES_AND_ACCESS) |
| 242 |
|
| 243 |
def template( |
| 244 |
self, |
| 245 |
variable: t.Any, # DTFIX-FUTURE: once we settle the new/old API boundaries, rename this (here and in other methods) |
| 246 |
*, |
| 247 |
options: TemplateOptions = TemplateOptions.DEFAULT, |
| 248 |
mode: TemplateMode = TemplateMode.DEFAULT, |
| 249 |
lazy_options: LazyOptions = LazyOptions.DEFAULT, |
| 250 |
) -> t.Any: |
| 251 |
"""Templates (possibly recursively) any given data as input.""" |
| 252 |
original_variable = variable |
| 253 |
|
| 254 |
for _attempt in range(TRANSFORM_CHAIN_LIMIT): |
| 255 |
if variable is None or (value_type := type(variable)) in IGNORE_SCALAR_VAR_TYPES: |
| 256 |
return variable # quickly ignore supported scalar types which are not be templated |
| 257 |
|
| 258 |
if is_expression := type(variable) is TemplateExpressionWrapper: # pylint: disable=unidiomatic-typecheck |
| 259 |
variable = variable.expression |
| 260 |
|
| 261 |
value_is_str = isinstance(variable, str) |
| 262 |
|
| 263 |
if template_ctx := TemplateContext.current(optional=True): |
| 264 |
stop_on_template = template_ctx.stop_on_template |
| 265 |
else: |
| 266 |
stop_on_template = False |
| 267 |
|
| 268 |
if mode is TemplateMode.STOP_ON_TEMPLATE: |
| 269 |
stop_on_template = True |
| 270 |
|
| 271 |
with ( |
| 272 |
TemplateContext(template_value=variable, templar=self, options=options, stop_on_template=stop_on_template) as ctx, |
| 273 |
DeprecatedAccessAuditContext.when(ctx.is_top_level), |
| 274 |
JinjaCallContext(accept_lazy_markers=True), # let default Jinja marker behavior apply, since we're descending into a new template |
| 275 |
): |
| 276 |
try: |
| 277 |
if not value_is_str: |
| 278 |
# transforms are currently limited to non-str types as an optimization |
| 279 |
if (transform := _type_transform_mapping.get(value_type)) and value_type.__name__ not in lazy_options.unmask_type_names: |
| 280 |
variable = transform(variable) |
| 281 |
continue |
| 282 |
|
| 283 |
template_result = _AnsibleLazyTemplateMixin._try_create(variable, lazy_options) |
| 284 |
elif not lazy_options.template: |
| 285 |
template_result = variable |
| 286 |
elif not is_expression and not is_possibly_template(variable, options.overrides): |
| 287 |
template_result = variable |
| 288 |
elif not self._trust_check(variable, skip_handler=stop_on_template): |
| 289 |
template_result = variable |
| 290 |
elif stop_on_template: |
| 291 |
raise TemplateEncountered() |
| 292 |
else: |
| 293 |
compiled_template = self._compile_expression(variable, options) if is_expression else self._compile_template(variable, options) |
| 294 |
|
| 295 |
template_result = compiled_template(self.available_variables) |
| 296 |
template_result = self._post_render_mutation(variable, template_result, options) |
| 297 |
except TemplateEncountered: |
| 298 |
raise |
| 299 |
except Exception as ex: |
| 300 |
template_result = defer_template_error(ex, variable, is_expression=is_expression) |
| 301 |
|
| 302 |
if ctx.is_top_level or mode is TemplateMode.ALWAYS_FINALIZE: |
| 303 |
template_result = self._finalize_top_level_template_result( |
| 304 |
variable, options, template_result, stop_on_container=mode is TemplateMode.STOP_ON_CONTAINER |
| 305 |
) |
| 306 |
|
| 307 |
return template_result |
| 308 |
|
| 309 |
raise AnsibleTemplateTransformLimitError(obj=original_variable) |
| 310 |
|
| 311 |
@staticmethod |
| 312 |
def _finalize_top_level_template_result( |
| 313 |
variable: t.Any, |
| 314 |
options: TemplateOptions, |
| 315 |
template_result: t.Any, |
| 316 |
is_expression: bool = False, |
| 317 |
stop_on_container: bool = False, |
| 318 |
) -> t.Any: |
| 319 |
""" |
| 320 |
This method must be called for expressions and top-level templates to recursively finalize the result. |
| 321 |
This renders any embedded templates and triggers `Marker` and omit behaviors. |
| 322 |
""" |
| 323 |
try: |
| 324 |
if template_result is Omit: |
| 325 |
# When the template result is Omit, raise an AnsibleValueOmittedError if value_for_omit is Omit, otherwise return value_for_omit. |
| 326 |
# Other occurrences of Omit will simply drop out of containers during _finalize_template_result. |
| 327 |
if options.value_for_omit is Omit: |
| 328 |
raise AnsibleValueOmittedError() |
| 329 |
|
| 330 |
return options.value_for_omit # trust that value_for_omit is an allowed type |
| 331 |
|
| 332 |
if stop_on_container and type(template_result) in AnsibleTaggedObject._collection_types: |
| 333 |
# Use of stop_on_container implies the caller will perform necessary checks on values, |
| 334 |
# most likely by passing them back into the templating system. |
| 335 |
try: |
| 336 |
return template_result._non_lazy_copy() |
| 337 |
except AttributeError: |
| 338 |
return template_result # non-lazy containers are returned as-is |
| 339 |
|
| 340 |
return _finalize_template_result(template_result, FinalizeMode.TOP_LEVEL) |
| 341 |
except TemplateEncountered: |
| 342 |
raise |
| 343 |
except Exception as ex: |
| 344 |
raise_from: BaseException |
| 345 |
|
| 346 |
if isinstance(ex, MarkerError): |
| 347 |
exception_to_raise = ex.source._as_exception() |
| 348 |
|
| 349 |
# MarkerError is never suitable for use as the cause of another exception, it is merely a raiseable container for the source marker |
| 350 |
# used for flow control (so its stack trace is rarely useful). However, if the source derives from a ExceptionMarker, its contained |
| 351 |
# exception (previously raised) should be used as the cause. Other sources do not contain exceptions, so cannot provide a cause. |
| 352 |
raise_from = exception_to_raise if isinstance(ex.source, ExceptionMarker) else None |
| 353 |
else: |
| 354 |
exception_to_raise = ex |
| 355 |
raise_from = ex |
| 356 |
|
| 357 |
exception_to_raise = create_template_error(exception_to_raise, variable, is_expression) |
| 358 |
|
| 359 |
if exception_to_raise is ex: |
| 360 |
raise # when the exception to raise is the active exception, just re-raise it |
| 361 |
|
| 362 |
if exception_to_raise is raise_from: |
| 363 |
raise_from = exception_to_raise.__cause__ # preserve the exception's cause, if any, otherwise no cause will be used |
| 364 |
|
| 365 |
raise exception_to_raise from raise_from # always raise from something to avoid the currently active exception becoming __context__ |
| 366 |
|
| 367 |
def _compile_template(self, template: str, options: TemplateOptions) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: |
| 368 |
# NOTE: Creating an overlay that lives only inside _compile_template means that overrides are not applied |
| 369 |
# when templating nested variables, where Templar.environment is used, not the overlay. They are, however, |
| 370 |
# applied to includes and imports. |
| 371 |
try: |
| 372 |
stripped_template, env = self._create_overlay(template, options.overrides) |
| 373 |
|
| 374 |
with _TemplateCompileContext(escape_backslashes=options.escape_backslashes): |
| 375 |
return t.cast(AnsibleTemplate, env.from_string(stripped_template)) |
| 376 |
except Exception as ex: |
| 377 |
return self._defer_jinja_compile_error(ex, template, False) |
| 378 |
|
| 379 |
def _compile_expression(self, expression: str, options: TemplateOptions) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: |
| 380 |
""" |
| 381 |
Compile a Jinja expression, applying optional compile-time behavior via an environment overlay (if needed). The overlay is |
| 382 |
necessary to avoid mutating settings on the Templar's shared environment, which could be visible to other code running concurrently. |
| 383 |
In the specific case of escape_backslashes, the setting only applies to a top-level template at compile-time, not runtime, to |
| 384 |
ensure that any nested template calls (e.g., include and import) do not inherit the (lack of) escaping behavior. |
| 385 |
""" |
| 386 |
try: |
| 387 |
with _TemplateCompileContext(escape_backslashes=options.escape_backslashes): |
| 388 |
return AnsibleTemplateExpression(self.environment.compile_expression(expression, False)) |
| 389 |
except Exception as ex: |
| 390 |
return self._defer_jinja_compile_error(ex, expression, True) |
| 391 |
|
| 392 |
def _defer_jinja_compile_error(self, ex: Exception, variable: str, is_expression: bool) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: |
| 393 |
deferred_error = defer_template_error(ex, variable, is_expression=is_expression) |
| 394 |
|
| 395 |
def deferred_exception(_jinja_vars: c.Mapping[str, t.Any]) -> t.Any: |
| 396 |
# a template/expression compile error always results in a single node representing the compile error |
| 397 |
return self.marker_behavior.handle_marker(deferred_error) |
| 398 |
|
| 399 |
return deferred_exception |
| 400 |
|
| 401 |
def _post_render_mutation(self, template: str, result: t.Any, options: TemplateOptions) -> t.Any: |
| 402 |
if options.preserve_trailing_newlines and isinstance(result, str): |
| 403 |
# The low level calls above do not preserve the newline |
| 404 |
# characters at the end of the input data, so we |
| 405 |
# calculate the difference in newlines and append them |
| 406 |
# to the resulting output for parity |
| 407 |
# |
| 408 |
# Using AnsibleEnvironment's keep_trailing_newline instead would |
| 409 |
# result in change in behavior when trailing newlines |
| 410 |
# would be kept also for included templates, for example: |
| 411 |
# "Hello {% include 'world.txt' %}!" would render as |
| 412 |
# "Hello world\n!\n" instead of "Hello world!\n". |
| 413 |
data_newlines = self._count_newlines_from_end(template) |
| 414 |
res_newlines = self._count_newlines_from_end(result) |
| 415 |
|
| 416 |
if data_newlines > res_newlines: |
| 417 |
newlines = options.overrides.newline_sequence * (data_newlines - res_newlines) |
| 418 |
result = AnsibleTagHelper.tag_copy(result, result + newlines) |
| 419 |
|
| 420 |
# If the input string template was source-tagged and the result is not, propagate the source tag to the new value. |
| 421 |
# This provides further contextual information when a template-derived value/var causes an error. |
| 422 |
if not Origin.is_tagged_on(result) and (origin := Origin.get_tag(template)): |
| 423 |
try: |
| 424 |
result = origin.tag(result) |
| 425 |
except NotTaggableError: |
| 426 |
pass # best effort- if we can't, oh well |
| 427 |
|
| 428 |
return result |
| 429 |
|
| 430 |
def is_template(self, data: t.Any, overrides: TemplateOverrides = TemplateOverrides.DEFAULT) -> bool: |
| 431 |
""" |
| 432 |
Evaluate the input data to determine if it contains a template, even if that template is invalid. Containers will be recursively searched. |
| 433 |
Objects subject to template-time transforms that do not yield a template are not considered templates by this method. |
| 434 |
Gating a conditional call to `template` with this method is redundant and inefficient -- request templating unconditionally instead. |
| 435 |
""" |
| 436 |
options = TemplateOptions(overrides=overrides) if overrides is not TemplateOverrides.DEFAULT else TemplateOptions.DEFAULT |
| 437 |
|
| 438 |
try: |
| 439 |
self.template(data, options=options, mode=TemplateMode.STOP_ON_TEMPLATE) |
| 440 |
except TemplateEncountered: |
| 441 |
return True |
| 442 |
else: |
| 443 |
return False |
| 444 |
|
| 445 |
def resolve_to_container(self, variable: t.Any, options: TemplateOptions = TemplateOptions.DEFAULT) -> t.Any: |
| 446 |
""" |
| 447 |
Recursively resolve scalar string template input, stopping at the first container encountered (if any). |
| 448 |
Used for e.g., partial templating of task arguments, where the plugin needs to handle final resolution of some args internally. |
| 449 |
""" |
| 450 |
return self.template(variable, options=options, mode=TemplateMode.STOP_ON_CONTAINER) |
| 451 |
|
| 452 |
def evaluate_expression( |
| 453 |
self, |
| 454 |
expression: str, |
| 455 |
*, |
| 456 |
local_variables: dict[str, t.Any] | None = None, |
| 457 |
escape_backslashes: bool = True, |
| 458 |
_render_jinja_const_template: bool = False, |
| 459 |
) -> t.Any: |
| 460 |
""" |
| 461 |
Evaluate a trusted string expression and return its result. |
| 462 |
Optional local variables may be provided, which can only be referenced directly by the given expression. |
| 463 |
""" |
| 464 |
if not isinstance(expression, str): |
| 465 |
raise TypeError(f"Expressions must be {str!r}, got {type(expression)!r}.") |
| 466 |
|
| 467 |
options = TemplateOptions(escape_backslashes=escape_backslashes, preserve_trailing_newlines=False) |
| 468 |
|
| 469 |
with ( |
| 470 |
TemplateContext(template_value=expression, templar=self, options=options, _render_jinja_const_template=_render_jinja_const_template) as ctx, |
| 471 |
DeprecatedAccessAuditContext.when(ctx.is_top_level), |
| 472 |
): |
| 473 |
try: |
| 474 |
if not TrustedAsTemplate.is_tagged_on(expression): |
| 475 |
raise TemplateTrustCheckFailedError(obj=expression) |
| 476 |
|
| 477 |
template_variables = ChainMap(local_variables, self.available_variables) if local_variables else self.available_variables |
| 478 |
compiled_template = self._compile_expression(expression, options) |
| 479 |
|
| 480 |
template_result = compiled_template(template_variables) |
| 481 |
template_result = self._post_render_mutation(expression, template_result, options) |
| 482 |
except Exception as ex: |
| 483 |
template_result = defer_template_error(ex, expression, is_expression=True) |
| 484 |
|
| 485 |
return self._finalize_top_level_template_result(expression, options, template_result, is_expression=True) |
| 486 |
|
| 487 |
_BROKEN_CONDITIONAL_ALLOWED_FRAGMENT = 'Broken conditionals are currently allowed because the `ALLOW_BROKEN_CONDITIONALS` configuration option is enabled.' |
| 488 |
_CONDITIONAL_AS_TEMPLATE_MSG = 'Conditionals should not be surrounded by templating delimiters such as {{ }} or {% %}.' |
| 489 |
|
| 490 |
def _strip_conditional_handle_empty(self, conditional) -> t.Any: |
| 491 |
""" |
| 492 |
Strips leading/trailing whitespace from the input expression. |
| 493 |
If `ALLOW_BROKEN_CONDITIONALS` is enabled, None/empty is coerced to True (legacy behavior, deprecated). |
| 494 |
Otherwise, None/empty results in a broken conditional error being raised. |
| 495 |
""" |
| 496 |
if isinstance(conditional, str): |
| 497 |
# Leading/trailing whitespace on conditional expressions is not a problem, except we can't tell if the expression is empty (which *is* a problem). |
| 498 |
# Always strip conditional input strings. Neither conditional expressions nor all-template conditionals have legit reasons to preserve |
| 499 |
# surrounding whitespace, and they complicate detection and processing of all-template fallback cases. |
| 500 |
conditional = AnsibleTagHelper.tag_copy(conditional, conditional.strip()) |
| 501 |
|
| 502 |
if conditional in (None, ''): |
| 503 |
# deprecated backward-compatible behavior; None/empty input conditionals are always True |
| 504 |
if _TemplateConfig.allow_broken_conditionals: |
| 505 |
_display.deprecated( |
| 506 |
msg='Empty conditional expression was evaluated as True.', |
| 507 |
help_text=self._BROKEN_CONDITIONAL_ALLOWED_FRAGMENT, |
| 508 |
obj=conditional, |
| 509 |
version='2.23', |
| 510 |
) |
| 511 |
|
| 512 |
return True |
| 513 |
|
| 514 |
raise AnsibleBrokenConditionalError("Empty conditional expressions are not allowed.", obj=conditional) |
| 515 |
|
| 516 |
return conditional |
| 517 |
|
| 518 |
def _normalize_and_evaluate_conditional(self, conditional: str | bool) -> t.Any: |
| 519 |
"""Validate and normalize a conditional input value, resolving allowed embedded template cases and evaluating the resulting expression.""" |
| 520 |
conditional = self._strip_conditional_handle_empty(conditional) |
| 521 |
|
| 522 |
# this must follow `_strip_conditional_handle_empty`, since None/empty are coerced to bool (deprecated) |
| 523 |
if type(conditional) is bool: # pylint: disable=unidiomatic-typecheck |
| 524 |
return conditional |
| 525 |
|
| 526 |
try: |
| 527 |
if not isinstance(conditional, str): |
| 528 |
if _TemplateConfig.allow_broken_conditionals: |
| 529 |
# because the input isn't a string, the result will never be a bool; the broken conditional warning in the caller will apply on the result |
| 530 |
return self.template(conditional, mode=TemplateMode.ALWAYS_FINALIZE) |
| 531 |
|
| 532 |
raise AnsibleBrokenConditionalError(message="Conditional expressions must be strings.", obj=conditional) |
| 533 |
|
| 534 |
if is_possibly_all_template(conditional): |
| 535 |
# Indirection of trusted expressions is always allowed. If the expression appears to be entirely wrapped in template delimiters, |
| 536 |
# we must resolve it. e.g. `when: "{{ some_var_resolving_to_a_trusted_expression_string }}"`. |
| 537 |
# Some invalid meta-templating corner cases may sneak through here (e.g., `when: '{{ "foo" }} == {{ "bar" }}'`); these will |
| 538 |
# result in an untrusted expression error. |
| 539 |
result = self.template(conditional, mode=TemplateMode.ALWAYS_FINALIZE) |
| 540 |
result = self._strip_conditional_handle_empty(result) |
| 541 |
|
| 542 |
if not isinstance(result, str): |
| 543 |
_display.deprecated(msg=self._CONDITIONAL_AS_TEMPLATE_MSG, obj=conditional, version='2.23') |
| 544 |
|
| 545 |
return result # not an expression |
| 546 |
|
| 547 |
# The only allowed use of templates for conditionals is for indirect usage of an expression. |
| 548 |
# Any other usage should simply be an expression, not an attempt at meta templating. |
| 549 |
expression = result |
| 550 |
else: |
| 551 |
expression = conditional |
| 552 |
|
| 553 |
# Disable escape_backslashes when processing conditionals, to maintain backwards compatibility. |
| 554 |
# This is necessary because conditionals were previously evaluated using {% %}, which was *NOT* affected by escape_backslashes. |
| 555 |
# Now that conditionals use expressions, they would be affected by escape_backslashes if it was not disabled. |
| 556 |
return self.evaluate_expression(expression, escape_backslashes=False, _render_jinja_const_template=True) |
| 557 |
|
| 558 |
except AnsibleUndefinedVariable as ex: |
| 559 |
# DTFIX-FUTURE: we're only augmenting the message for context here; once we have proper contextual tracking, we can dump the re-raise |
| 560 |
raise AnsibleUndefinedVariable("Error while evaluating conditional.", obj=conditional) from ex |
| 561 |
|
| 562 |
def evaluate_conditional(self, conditional: str | bool) -> bool: |
| 563 |
""" |
| 564 |
Evaluate a trusted string expression or boolean and return its boolean result. A non-boolean result will raise `AnsibleBrokenConditionalError`. |
| 565 |
The ALLOW_BROKEN_CONDITIONALS configuration option can temporarily relax this requirement, allowing truthy conditionals to succeed. |
| 566 |
""" |
| 567 |
result = self._normalize_and_evaluate_conditional(conditional) |
| 568 |
|
| 569 |
if isinstance(result, bool): |
| 570 |
return result |
| 571 |
|
| 572 |
bool_result = bool(result) |
| 573 |
|
| 574 |
result_origin = Origin.get_tag(result) or Origin.UNKNOWN |
| 575 |
|
| 576 |
msg = ( |
| 577 |
f'Conditional result ({bool_result}) was derived from value of type {native_type_name(result)!r} at {str(result_origin)!r}. ' |
| 578 |
'Conditionals must have a boolean result.' |
| 579 |
) |
| 580 |
|
| 581 |
if _TemplateConfig.allow_broken_conditionals: |
| 582 |
_display.deprecated( |
| 583 |
msg=msg, |
| 584 |
obj=conditional, |
| 585 |
help_text=self._BROKEN_CONDITIONAL_ALLOWED_FRAGMENT, |
| 586 |
version='2.23', |
| 587 |
) |
| 588 |
|
| 589 |
return bool_result |
| 590 |
|
| 591 |
raise AnsibleBrokenConditionalError(msg, obj=conditional) |
| 592 |
|
| 593 |
@staticmethod |
| 594 |
def _trust_check(value: str, skip_handler: bool = False) -> bool: |
| 595 |
""" |
| 596 |
Return True if the given value is trusted for templating, otherwise return False. |
| 597 |
When the value is not trusted, a warning or error may be generated, depending on configuration. |
| 598 |
""" |
| 599 |
if TrustedAsTemplate.is_tagged_on(value): |
| 600 |
return True |
| 601 |
|
| 602 |
if not skip_handler: |
| 603 |
with Skippable, _TemplateConfig.untrusted_template_handler.handle(TemplateTrustCheckFailedError, skip_on_ignore=True): |
| 604 |
raise TemplateTrustCheckFailedError(obj=value) |
| 605 |
|
| 606 |
return False |