Documentation
¶
Overview ¶
Package template implements Ansible's templating semantics on top of a Jinja2-compatible engine (github.com/nikolalohinski/gonja/v2): string interpolation with {{ }}, control structures with {% %}, Ansible's own filter and test library on top of the Jinja2 built-ins, and Ansible's rule that a value which is a SINGLE {{ expr }} with nothing else around it renders to the expression's native type (list, dict, int, bool...), not a string.
Index ¶
- Constants
- Variables
- func IsOmit(v any) bool
- func IsTemplate(s string) bool
- func PythonRepr(v any) string
- func PythonStr(v any) string
- func PythonTypeName(v any) string
- func ToJSON(v any, indent int) (string, error)
- type Engine
- func (e *Engine) Eval(exprSrc string, data map[string]any) (any, error)
- func (e *Engine) EvalBool(exprSrc string, data map[string]any) (bool, error)
- func (e *Engine) HasLookup(name string) bool
- func (e *Engine) JinjaStringEscapes() *Engine
- func (e *Engine) Lookup(name string, terms []any, variables map[string]any, kwargs map[string]any) ([]any, error)
- func (e *Engine) RegisterFilter(name string, fn exec.FilterFunction) error
- func (e *Engine) RegisterTest(name string, fn TestFunc) error
- func (e *Engine) Render(src string, data map[string]any) (string, error)
- func (e *Engine) RenderValue(raw any, data map[string]any) (any, error)
- type TestFunc
Constants ¶
const FilterFailurePrefix = "The filter plugin '"
FilterFailurePrefix is how this package words a filter plugin's own refusal, and it is real's wording:
The filter plugin 'ansible.builtin.mandatory' failed: <reason>
It is exported because it is a CONTRACT with the playbook engine, not a coincidence: gonja wraps whatever a filter returns in several layers of its own prose ("unable to evaluate filter &{<Token...}"), which real has no equivalent of and never prints, and the engine finds the part real would have printed by looking for this prefix. Cutting on a boundary the other side guarantees beats a list of fragments to strip, which stops matching the day gonja rewords one.
The same reasoning as the lookup plugin's own prefix, one layer down.
Variables ¶
var Omit omitType
Omit is the sentinel value the "omit" global evaluates to. A task argument written as "{{ x | default(omit) }}" renders to this value when x is undefined, and RenderValue drops the containing map key or list item rather than passing Omit through to a module.
Functions ¶
func IsTemplate ¶
IsTemplate reports whether s contains any Jinja2 delimiter ({{, {%, or {#) and therefore needs rendering at all.
func PythonRepr ¶ added in v0.22.0
PythonRepr renders a value the way Python's repr() does.
func PythonStr ¶ added in v0.22.0
PythonStr renders a value the way Python's str() does, which is what real Ansible's loop labels use: `(item=...)` on every ok/skipping line of a looping task.
The rule that makes this more than a format verb: str() of a CONTAINER uses repr() of its elements. So a bare string item prints unquoted while the same string inside a list prints quoted — measured, `(item=plain)` beside `(item=['a', 1])`.
Go's %v gave `map[k:v]` and `[1 <nil>]` where Python gives `{'k': 'v'}` and `[1, None]`, so every loop over anything but a scalar diverged.
func PythonTypeName ¶ added in v0.18.0
PythonTypeName is the name Python would give this value's type — 'str', 'int', 'list', 'dict', 'NoneType' and so on. It is what the type_debug filter reports, exported because a caller that has to explain a value to a user in Ansible's own words needs the same name: the playbook engine's "Conditional result was derived from value of type 'str'" is real Ansible's wording, and forming that name a second time is how two answers drift apart.
func ToJSON ¶ added in v0.12.0
ToJSON renders v the way Python's json.dumps does, which is what real Ansible's own output looks like wherever it prints a result as JSON — the to_json filter here, and the failure lines go-ansible/playbook's default callback writes. Exported so that second caller renders identically rather than growing its own emitter that can drift.
indent 0 gives json.dumps' compact-with-spaces default (", " and ": "); a positive indent gives its pretty form. Keys are always sorted — see filterToJSON for why insertion order is not recoverable here.
Types ¶
type Engine ¶
type Engine struct {
// OnWarning, when set, receives warnings a render would otherwise
// have nowhere to go — currently only a lookup called with
// errors=warn, which real Ansible reports through its own Display
// layer. Left nil, such a lookup degrades to errors=ignore.
OnWarning func(msg string)
// contains filtered or unexported fields
}
Engine renders Ansible-flavored Jinja2 templates and expressions.
func (*Engine) Eval ¶
Eval evaluates a single Jinja2 expression (no {{ }} wrapper — e.g. the raw text of an Ansible `when:` condition, or the inside of a wholeExpression string) and returns its native Go value.
func (*Engine) EvalBool ¶
EvalBool evaluates exprSrc and applies Ansible/Jinja2 truthiness — the semantics of a `when:` condition.
func (*Engine) HasLookup ¶ added in v0.21.0
HasLookup reports whether a lookup plugin of this name exists — what the playbook parser needs to tell a `with_<known>` key apart from a module whose name happens to start with "with_".
func (*Engine) JinjaStringEscapes ¶ added in v0.17.0
New returns an Engine with Jinja2's built-in filters/tests plus Ansible's filter and test library. JinjaStringEscapes switches this engine from Ansible's RAW string literals to plain Jinja2's escape processing, where "x\ny" is three characters and 'C:\Users' is an error.
Real ansible-core 2.21 uses BOTH, depending on where the expression was written — measured with one expression in two places:
{{ "x\ny" | length }} inline in a playbook 4 (raw)
{{ "x\ny" | length }} inside a .j2 file 3 (Jinja2)
So an engine rendering a template FILE for the `template` module sets this, and one evaluating a playbook's own expressions does not. It is off by default because the playbook engine is the larger caller and its semantics are the ones a task author meets first.
func (*Engine) Lookup ¶ added in v0.21.0
func (e *Engine) Lookup(name string, terms []any, variables map[string]any, kwargs map[string]any) ([]any, error)
Lookup runs a lookup plugin directly, as `with_<name>` needs: it is the same call `lookup('<name>', ...)` makes from a template, with wantlist forced on so the result is always the plugin's own list.
It exists because with_* lives in the playbook engine rather than in a template, and real resolves those two through exactly one path — with_dict IS the dict lookup. Two paths would drift.
func (*Engine) RegisterFilter ¶ added in v0.33.0
func (e *Engine) RegisterFilter(name string, fn exec.FilterFunction) error
RegisterFilter adds a custom filter callable from any template rendered by this engine, like Ansible's filter plugins. Filters resolve by name at each application, so a registration is visible to subsequent filter uses -- including inside an already started Render/Eval. Register before rendering begins for deterministic behaviour. Registering an existing name (built-ins, Ansible's library, the null-aware overrides) returns an error instead of replacing it.
func (*Engine) RegisterTest ¶ added in v0.33.0
RegisterTest adds a custom test callable as `x is name` in any template rendered by this engine, like Ansible's test plugins -- the companion to RegisterFilter, since Ansible extends Jinja2 with both and this engine's test set was assembled inside New() behind the same unexported field.
The same rules as RegisterFilter: registration is per-engine (New builds a fresh set rather than sharing the package-level one), tests resolve by name at each application, and an existing name -- a built-in, Ansible's own library -- returns an error instead of being replaced. Register before rendering begins.
⚠ gonja's Register is synchronized per call but NOT atomic: it asks Exists, which takes and releases the lock, and only then takes the lock again to write. Two goroutines registering the same name can both pass that check. Registering from one goroutine before rendering starts is the contract, not merely the advice.
func (*Engine) Render ¶
Render renders a full template string (text mixed with {{ }} / {% %}) to its string form.
func (*Engine) RenderValue ¶
RenderValue applies Ansible's templating rule to an arbitrary decoded YAML value: strings are templated (with the whole-expression rule preserving native types), and lists/maps are walked recursively so a nested `{{ }}` anywhere in a task's arguments is resolved. Non-string scalars pass through unchanged.
A value that renders to Omit (see omit.go — typically reached via `default(omit)`) is dropped entirely: from a map, the whole key disappears; from a list, the item disappears — matching real Ansible's own "Omit values remaining in template results will be automatically dropped during template finalization." A bare top-level result of exactly Omit, with no containing map or list to drop it from, is an error, matching real Ansible's own AnsibleValueOmittedError.
type TestFunc ¶ added in v0.33.0
TestFunc is the shape a custom Jinja test must have: it receives the value on the left of `is`, the test's own arguments, and answers true or false.
It is spelled out here rather than reusing gonja's own exec.TestFunction because that one is `any` -- gonja widened it to accept a legacy first argument of *exec.Context as well as *exec.Evaluator, and the shape is then checked by reflection at registration time. Taking `any` would mean a caller learns about a wrong signature from an error value at run time, where RegisterFilter's gonja type (a real func type) lets the compiler say so. A new API should not inherit someone else's backwards compatibility, so this one is typed and every test in this package already has this shape.