Debian Codegraph @

lib/ansible/_internal/_templating/_chain_templar.py

raw
1 from __future__ import annotations
2
3 import collections.abc as c
4 import itertools
5 import typing as t
6
7 from ansible.errors import AnsibleValueOmittedError, AnsibleError
8
9 from ._engine import TemplateEngine
10
11
12 class ChainTemplar:
13 """A basic variable layering mechanism that supports templating and obliteration of `omit` values."""
14
15 def __init__(self, *sources: c.Mapping, templar: TemplateEngine) -> None:
16 self.sources = sources
17 self.templar = templar
18
19 def template(self, key: t.Any, value: t.Any) -> t.Any:
20 """
21 Render the given value using the templar.
22 Intended to be overridden by subclasses.
23 """
24 return self.templar.template(value)
25
26 def get(self, key: t.Any) -> t.Any:
27 """Get the value for the given key, templating the result before returning it."""
28 for source in self.sources:
29 if key not in source:
30 continue
31
32 value = source[key]
33
34 try:
35 return self.template(key, value)
36 except AnsibleValueOmittedError:
37 break # omit == obliterate - matches historical behavior where dict layers were squashed before templating was applied
38 except Exception as ex:
39 raise AnsibleError(f'Error while resolving value for {key!r}.', obj=value) from ex
40
41 raise KeyError(key)
42
43 def keys(self) -> t.Iterable[t.Any]:
44 """
45 Returns a sorted iterable of all keys present in all source layers, without templating associated values.
46 Values that resolve to `omit` are thus included.
47 """
48 return sorted(set(itertools.chain.from_iterable(self.sources)))
49
50 def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:
51 """
52 Returns a sorted iterable of (key, templated value) tuples.
53 Any tuple where the templated value resolves to `omit` will not be included in the result.
54 """
55 for key in self.keys():
56 try:
57 yield key, self.get(key)
58 except KeyError:
59 pass
60
61 def as_dict(self) -> dict[t.Any, t.Any]:
62 """Returns a dict representing all layers, squashed and templated, with `omit` values dropped."""
63 return dict(self.items())