| 1 |
"""Jinja template plugins (filters, tests, lookups) and custom global functions.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import collections.abc as c |
| 6 |
import dataclasses |
| 7 |
import datetime |
| 8 |
import functools |
| 9 |
import inspect |
| 10 |
import re |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from jinja2 import defaults |
| 14 |
|
| 15 |
from ansible.module_utils._internal._ambient_context import AmbientContextBase |
| 16 |
from ansible.module_utils.common.collections import is_sequence |
| 17 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 18 |
from ansible._internal._datatag._tags import TrustedAsTemplate |
| 19 |
from ansible.plugins import AnsibleJinja2Plugin |
| 20 |
from ansible.plugins.loader import lookup_loader, Jinja2Loader |
| 21 |
from ansible.plugins.lookup import LookupBase |
| 22 |
from ansible.utils.display import Display |
| 23 |
|
| 24 |
from ._datatag import _JinjaConstTemplate |
| 25 |
from ._errors import AnsibleTemplatePluginRuntimeError, AnsibleTemplatePluginLoadError, AnsibleTemplatePluginNotFoundError |
| 26 |
from ._jinja_common import MarkerError, _TemplateConfig, get_first_marker_arg, Marker, JinjaCallContext, CapturedExceptionMarker |
| 27 |
from ._lazy_containers import lazify_container_kwargs, lazify_container_args, lazify_container, _AnsibleLazyTemplateMixin |
| 28 |
from ._utils import LazyOptions, TemplateContext |
| 29 |
|
| 30 |
_display = Display() |
| 31 |
|
| 32 |
_ITERATOR_TYPES: t.Final = (c.Iterator, c.ItemsView, c.KeysView, c.ValuesView, range) |
| 33 |
|
| 34 |
|
| 35 |
class JinjaPluginIntercept(c.MutableMapping): |
| 36 |
""" |
| 37 |
Simulated dict class that loads Jinja2Plugins at request |
| 38 |
otherwise all plugins would need to be loaded a priori. |
| 39 |
|
| 40 |
NOTE: plugin_loader still loads all 'builtin/legacy' at |
| 41 |
start so only collection plugins are really at request. |
| 42 |
""" |
| 43 |
|
| 44 |
def __init__(self, jinja_builtins: c.Mapping[str, AnsibleJinja2Plugin], plugin_loader: Jinja2Loader): |
| 45 |
super(JinjaPluginIntercept, self).__init__() |
| 46 |
|
| 47 |
self._plugin_loader = plugin_loader |
| 48 |
self._jinja_builtins = jinja_builtins |
| 49 |
self._wrapped_funcs: dict[str, t.Callable] = {} |
| 50 |
|
| 51 |
def _wrap_and_set_func(self, instance: AnsibleJinja2Plugin) -> t.Callable: |
| 52 |
if self._plugin_loader.type == 'filter': |
| 53 |
plugin_func = self._wrap_filter(instance) |
| 54 |
else: |
| 55 |
plugin_func = self._wrap_test(instance) |
| 56 |
|
| 57 |
self._wrapped_funcs[instance._load_name] = plugin_func |
| 58 |
|
| 59 |
return plugin_func |
| 60 |
|
| 61 |
def __getitem__(self, key: str) -> t.Callable: |
| 62 |
instance: AnsibleJinja2Plugin | None = None |
| 63 |
plugin_func: t.Callable[..., t.Any] | None |
| 64 |
|
| 65 |
if plugin_func := self._wrapped_funcs.get(key): |
| 66 |
return plugin_func |
| 67 |
|
| 68 |
try: |
| 69 |
instance = self._plugin_loader.get(key) |
| 70 |
except KeyError: |
| 71 |
# The plugin name was invalid or no plugin was found by that name. |
| 72 |
pass |
| 73 |
except Exception as ex: |
| 74 |
# An unexpected exception occurred. |
| 75 |
raise AnsibleTemplatePluginLoadError(self._plugin_loader.type, key) from ex |
| 76 |
|
| 77 |
if not instance: |
| 78 |
try: |
| 79 |
instance = self._jinja_builtins[key] |
| 80 |
except KeyError: |
| 81 |
raise AnsibleTemplatePluginNotFoundError(self._plugin_loader.type, key) from None |
| 82 |
|
| 83 |
plugin_func = self._wrap_and_set_func(instance) |
| 84 |
|
| 85 |
return plugin_func |
| 86 |
|
| 87 |
def __setitem__(self, key: str, value: t.Callable) -> None: |
| 88 |
self._wrap_and_set_func(self._plugin_loader._wrap_func(key, key, value)) |
| 89 |
|
| 90 |
def __delitem__(self, key): |
| 91 |
raise NotImplementedError() |
| 92 |
|
| 93 |
def __contains__(self, item: t.Any) -> bool: |
| 94 |
try: |
| 95 |
self.__getitem__(item) |
| 96 |
except AnsibleTemplatePluginLoadError: |
| 97 |
return True |
| 98 |
except AnsibleTemplatePluginNotFoundError: |
| 99 |
return False |
| 100 |
|
| 101 |
return True |
| 102 |
|
| 103 |
def __iter__(self): |
| 104 |
raise NotImplementedError() # dynamic container |
| 105 |
|
| 106 |
def __len__(self): |
| 107 |
raise NotImplementedError() # dynamic container |
| 108 |
|
| 109 |
@staticmethod |
| 110 |
def _invoke_plugin(instance: AnsibleJinja2Plugin, *args, **kwargs) -> t.Any: |
| 111 |
if not instance.accept_args_markers: |
| 112 |
if (first_marker := get_first_marker_arg(args, kwargs)) is not None: |
| 113 |
return first_marker |
| 114 |
|
| 115 |
try: |
| 116 |
with JinjaCallContext(accept_lazy_markers=instance.accept_lazy_markers): |
| 117 |
result = instance.j2_function(*lazify_container_args(args), **lazify_container_kwargs(kwargs)) |
| 118 |
|
| 119 |
if instance.plugin_type == 'filter': |
| 120 |
# ensure list conversion occurs under the call context |
| 121 |
result = _wrap_plugin_output(result) |
| 122 |
|
| 123 |
return result |
| 124 |
except MarkerError as ex: |
| 125 |
return ex.source |
| 126 |
except Exception as ex: |
| 127 |
try: |
| 128 |
raise AnsibleTemplatePluginRuntimeError(instance.plugin_type, instance.ansible_name) from ex # DTFIX-FUTURE: which name to use? PluginInfo? |
| 129 |
except AnsibleTemplatePluginRuntimeError as captured: |
| 130 |
return CapturedExceptionMarker(captured) |
| 131 |
|
| 132 |
def _wrap_test(self, instance: AnsibleJinja2Plugin) -> t.Callable: |
| 133 |
"""Intercept point for all test plugins to ensure that args are properly templated/lazified.""" |
| 134 |
|
| 135 |
@functools.wraps(instance.j2_function) |
| 136 |
def wrapper(*args, **kwargs) -> bool | Marker: |
| 137 |
result = self._invoke_plugin(instance, *args, **kwargs) |
| 138 |
|
| 139 |
if isinstance(result, Marker): |
| 140 |
return result |
| 141 |
|
| 142 |
if not isinstance(result, bool): |
| 143 |
template = TemplateContext.current().template_value |
| 144 |
|
| 145 |
_display.deprecated( |
| 146 |
msg=f"The test plugin {instance.ansible_name!r} returned a non-boolean result of type {type(result)!r}. " |
| 147 |
"Test plugins must have a boolean result.", |
| 148 |
obj=template, |
| 149 |
version="2.23", |
| 150 |
) |
| 151 |
|
| 152 |
result = bool(result) |
| 153 |
|
| 154 |
return result |
| 155 |
|
| 156 |
return wrapper |
| 157 |
|
| 158 |
def _wrap_filter(self, instance: AnsibleJinja2Plugin) -> t.Callable: |
| 159 |
"""Intercept point for all filter plugins to ensure that args are properly templated/lazified.""" |
| 160 |
|
| 161 |
@functools.wraps(instance.j2_function) |
| 162 |
def wrapper(*args, **kwargs) -> t.Any: |
| 163 |
result = self._invoke_plugin(instance, *args, **kwargs) |
| 164 |
|
| 165 |
return result |
| 166 |
|
| 167 |
return wrapper |
| 168 |
|
| 169 |
|
| 170 |
class _DirectCall: |
| 171 |
"""Functions/methods marked `_DirectCall` bypass Jinja Environment checks for `Marker`.""" |
| 172 |
|
| 173 |
_marker_attr: t.Final[str] = "_directcall" |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def mark[T: t.Callable](cls, src: T) -> T: |
| 177 |
setattr(src, cls._marker_attr, True) |
| 178 |
return src |
| 179 |
|
| 180 |
@classmethod |
| 181 |
def is_marked(cls, value: t.Callable) -> bool: |
| 182 |
return callable(value) and getattr(value, cls._marker_attr, False) |
| 183 |
|
| 184 |
|
| 185 |
@_DirectCall.mark |
| 186 |
def _query(plugin_name: str, /, *args, **kwargs) -> t.Any: |
| 187 |
"""wrapper for lookup, force wantlist true""" |
| 188 |
kwargs['wantlist'] = True |
| 189 |
return _invoke_lookup(plugin_name=plugin_name, lookup_terms=list(args), lookup_kwargs=kwargs) |
| 190 |
|
| 191 |
|
| 192 |
@_DirectCall.mark |
| 193 |
def _lookup(plugin_name: str, /, *args, **kwargs) -> t.Any: |
| 194 |
# convert the args tuple to a list, since some plugins make a poor assumption that `run.args` is a list |
| 195 |
return _invoke_lookup(plugin_name=plugin_name, lookup_terms=list(args), lookup_kwargs=kwargs) |
| 196 |
|
| 197 |
|
| 198 |
@dataclasses.dataclass |
| 199 |
class _LookupContext(AmbientContextBase): |
| 200 |
"""Ambient context that wraps lookup execution, providing information about how it was invoked.""" |
| 201 |
|
| 202 |
invoked_as_with: bool |
| 203 |
|
| 204 |
|
| 205 |
@_DirectCall.mark |
| 206 |
def _invoke_lookup(*, plugin_name: str, lookup_terms: list, lookup_kwargs: dict[str, t.Any], invoked_as_with: bool = False) -> t.Any: |
| 207 |
templar = TemplateContext.current().templar |
| 208 |
|
| 209 |
from ansible import template as _template |
| 210 |
|
| 211 |
try: |
| 212 |
instance: LookupBase | None = lookup_loader.get(plugin_name, loader=templar._loader, templar=_template.Templar._from_template_engine(templar)) |
| 213 |
except Exception as ex: |
| 214 |
raise AnsibleTemplatePluginLoadError('lookup', plugin_name) from ex |
| 215 |
|
| 216 |
if instance is None: |
| 217 |
raise AnsibleTemplatePluginNotFoundError('lookup', plugin_name) |
| 218 |
|
| 219 |
# if the lookup doesn't understand `Marker` and there's at least one in the top level, short-circuit by returning the first one we found |
| 220 |
if not instance.accept_args_markers and (first_marker := get_first_marker_arg(lookup_terms, lookup_kwargs)) is not None: |
| 221 |
return first_marker |
| 222 |
|
| 223 |
# don't pass these through to the lookup |
| 224 |
wantlist = lookup_kwargs.pop('wantlist', False) |
| 225 |
errors = lookup_kwargs.pop('errors', 'strict') |
| 226 |
|
| 227 |
with JinjaCallContext(accept_lazy_markers=instance.accept_lazy_markers): |
| 228 |
try: |
| 229 |
if _TemplateConfig.allow_embedded_templates: |
| 230 |
# for backwards compat, only trust constant templates in lookup terms |
| 231 |
with JinjaCallContext(accept_lazy_markers=True): |
| 232 |
# Force lazy marker support on for this call; the plugin's understanding is irrelevant, as is any existing context, since this backward |
| 233 |
# compat code always understands markers. |
| 234 |
lookup_terms = [templar.template(value) for value in _trust_jinja_constants(lookup_terms)] |
| 235 |
|
| 236 |
# since embedded template support is enabled, repeat the check for `Marker` on lookup_terms, since a template may render as a `Marker` |
| 237 |
if not instance.accept_args_markers and (first_marker := get_first_marker_arg(lookup_terms, {})) is not None: |
| 238 |
return first_marker |
| 239 |
else: |
| 240 |
lookup_terms = AnsibleTagHelper.tag_copy(lookup_terms, (lazify_container(value) for value in lookup_terms), value_type=list) |
| 241 |
|
| 242 |
with _LookupContext(invoked_as_with=invoked_as_with): |
| 243 |
# The lookup context currently only supports the internal use-case where `first_found` requires extra info when invoked via `with_first_found`. |
| 244 |
# The context may be public API in the future, but for now, other plugins should not implement this kind of dynamic behavior, |
| 245 |
# though we're stuck with it for backward compatibility on `first_found`. |
| 246 |
lookup_res = instance.run(lookup_terms, variables=templar.available_variables, **lazify_container_kwargs(lookup_kwargs)) |
| 247 |
|
| 248 |
# DTFIX-FUTURE: Consider allowing/requiring lookup plugins to declare how their result should be handled. |
| 249 |
# Currently, there are multiple behaviors that are less than ideal and poorly documented (or not at all): |
| 250 |
# * When `errors=warn` or `errors=ignore` the result is `None` unless `wantlist=True`, in which case the result is `[]`. |
| 251 |
# * The user must specify `wantlist=True` to receive the plugin return value unmodified. |
| 252 |
# A plugin can achieve similar results by wrapping its result in a list -- unless of course the user specifies `wantlist=True`. |
| 253 |
# * When `wantlist=True` is specified, the result is not guaranteed to be a list as the option implies (except on plugin error). |
| 254 |
# * Sequences are munged unless the user specifies `wantlist=True`: |
| 255 |
# * len() == 0 - Return an empty sequence. |
| 256 |
# * len() == 1 - Return the only element in the sequence. |
| 257 |
# * len() >= 2 when all elements are `str` - Return all the values joined into a single comma separated string. |
| 258 |
# * len() >= 2 when at least one element is not `str` - Return the sequence as-is. |
| 259 |
|
| 260 |
if not is_sequence(lookup_res): |
| 261 |
# DTFIX-FUTURE: deprecate return types which are not a list |
| 262 |
# previously non-Sequence return types were deprecated and then became an error in 2.18 |
| 263 |
# however, the deprecation message (and this error) mention `list` specifically rather than `Sequence` |
| 264 |
# letting non-list values through will trigger variable type checking warnings/errors |
| 265 |
raise TypeError(f'returned {type(lookup_res)} instead of {list}') |
| 266 |
|
| 267 |
except MarkerError as ex: |
| 268 |
return ex.source |
| 269 |
except Exception as ex: |
| 270 |
# DTFIX-FUTURE: convert this to the new error/warn/ignore context manager |
| 271 |
if errors == 'warn': |
| 272 |
_display.error_as_warning( |
| 273 |
msg=f'An error occurred while running the lookup plugin {plugin_name!r}.', |
| 274 |
exception=ex, |
| 275 |
) |
| 276 |
elif errors == 'ignore': |
| 277 |
_display.display(f'An error of type {type(ex)} occurred while running the lookup plugin {plugin_name!r}: {ex}', log_only=True) |
| 278 |
else: |
| 279 |
raise AnsibleTemplatePluginRuntimeError('lookup', plugin_name) from ex |
| 280 |
|
| 281 |
return [] if wantlist else None |
| 282 |
|
| 283 |
if not wantlist and lookup_res: |
| 284 |
# when wantlist=False the lookup result is either partially delaizified (single element) or fully delaizified (multiple elements) |
| 285 |
|
| 286 |
if len(lookup_res) == 1: |
| 287 |
lookup_res = lookup_res[0] |
| 288 |
else: |
| 289 |
try: |
| 290 |
lookup_res = ",".join(lookup_res) # for backwards compatibility, attempt to join `ran` into single string |
| 291 |
except TypeError: |
| 292 |
pass # for backwards compatibility, return `ran` as-is when the sequence contains non-string values |
| 293 |
|
| 294 |
return _wrap_plugin_output(lookup_res) |
| 295 |
|
| 296 |
|
| 297 |
def _now(utc=False, fmt=None): |
| 298 |
"""Jinja2 global function (now) to return current datetime, potentially formatted via strftime.""" |
| 299 |
if utc: |
| 300 |
now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) |
| 301 |
else: |
| 302 |
now = datetime.datetime.now() |
| 303 |
|
| 304 |
if fmt: |
| 305 |
return now.strftime(fmt) |
| 306 |
|
| 307 |
return now |
| 308 |
|
| 309 |
|
| 310 |
def _jinja_const_template_warning(value: object, is_conditional: bool) -> None: |
| 311 |
"""Issue a warning regarding embedded template usage.""" |
| 312 |
help_text = "Use inline expressions, for example: " |
| 313 |
|
| 314 |
if is_conditional: |
| 315 |
help_text += """`when: "{{ a_var }}" == 42` becomes `when: a_var == 42`""" |
| 316 |
else: |
| 317 |
help_text += """`msg: "{{ lookup('env', '{{ a_var }}') }}"` becomes `msg: "{{ lookup('env', a_var) }}"`""" |
| 318 |
|
| 319 |
# deprecated: description='disable embedded templates by default and deprecate the feature' core_version='2.23' |
| 320 |
_display.warning( |
| 321 |
msg="Jinja constant strings should not contain embedded templates. This feature will be disabled by default in ansible-core 2.23.", |
| 322 |
obj=value, |
| 323 |
help_text=help_text, |
| 324 |
) |
| 325 |
|
| 326 |
|
| 327 |
def _trust_jinja_constants(o: t.Any) -> t.Any: |
| 328 |
""" |
| 329 |
Recursively apply TrustedAsTemplate to values tagged with _JinjaConstTemplate and remove the tag. |
| 330 |
Only container types emitted by the Jinja compiler are checked, since others do not contain constants. |
| 331 |
This is used to provide backwards compatibility with historical lookup behavior for positional arguments. |
| 332 |
""" |
| 333 |
if _JinjaConstTemplate.is_tagged_on(o): |
| 334 |
_jinja_const_template_warning(o, is_conditional=False) |
| 335 |
|
| 336 |
return TrustedAsTemplate().tag(_JinjaConstTemplate.untag(o)) |
| 337 |
|
| 338 |
o_type = type(o) |
| 339 |
|
| 340 |
if o_type is dict: |
| 341 |
return {k: _trust_jinja_constants(v) for k, v in o.items()} |
| 342 |
|
| 343 |
if o_type in (list, tuple): |
| 344 |
return o_type(_trust_jinja_constants(v) for v in o) |
| 345 |
|
| 346 |
return o |
| 347 |
|
| 348 |
|
| 349 |
def _wrap_plugin_output(o: t.Any) -> t.Any: |
| 350 |
"""Utility method to ensure that iterators/generators returned from a plugins are consumed.""" |
| 351 |
if isinstance(o, _ITERATOR_TYPES): |
| 352 |
o = list(o) |
| 353 |
|
| 354 |
return _AnsibleLazyTemplateMixin._try_create(o, LazyOptions.SKIP_TEMPLATES) |
| 355 |
|
| 356 |
|
| 357 |
_PLUGIN_SOURCES = dict( |
| 358 |
filter=defaults.DEFAULT_FILTERS, |
| 359 |
test=defaults.DEFAULT_TESTS, |
| 360 |
) |
| 361 |
|
| 362 |
|
| 363 |
def _get_builtin_short_description(plugin: object) -> str: |
| 364 |
""" |
| 365 |
Make a reasonable effort to break a function docstring down to a single sentence. |
| 366 |
We can't use the full docstring due to embedded formatting, particularly RST. |
| 367 |
This isn't intended to be perfect, just good enough until we can write our own docs for these. |
| 368 |
""" |
| 369 |
value = re.split(r'(\.|!|\s\(|:\s)', inspect.getdoc(plugin), 1)[0].replace('\n', ' ') |
| 370 |
|
| 371 |
if value: |
| 372 |
value += '.' |
| 373 |
|
| 374 |
return value |
| 375 |
|
| 376 |
|
| 377 |
def get_jinja_builtin_plugin_descriptions(plugin_type: str) -> dict[str, str]: |
| 378 |
"""Returns a dictionary of Jinja builtin plugin names and their short descriptions.""" |
| 379 |
return {f'ansible.builtin.{name}': _get_builtin_short_description(plugin) for name, plugin in _PLUGIN_SOURCES[plugin_type].items() if name.isidentifier()} |