Documentation
¶
Overview ¶
Package playbook implements Ansible's playbook execution model: plays over an inventory pattern, tasks with when/loop/register/notify/ block-rescue-always, and handlers — wired to github.com/go-ansible/{inventory,vars,template,modules,facts} and github.com/go-remoteexec/transport.
Index ¶
- Constants
- func AdHocHostVars(inv *inventory.Inventory, host string, matched []string) map[string]any
- func ConfigFilePath() string
- func ConfigFileValueForEnv(envVar string) (string, bool)
- func DefaultConnect(ctx context.Context, hostName string, hostVars map[string]any) (remoteexec.Connection, error)
- func DisplayName(role, name, module string) string
- func ParseModuleArgs(module, args string) (map[string]any, error)
- func TagsSelect(effective, run, skip []string) bool
- type BaseCallback
- type Callback
- type CompatFinding
- type ConfigSetting
- type Connector
- type DefaultCallback
- type Engine
- type HostSummary
- type Play
- type PlayResult
- type Playbook
- type Result
- type RoleRef
- type RunResult
- type Task
- type UnresolvedModule
- type UnresolvedModulesError
- type VarPrompt
- type Warner
Constants ¶
const RedfishBackendVar = "goansible_redfish_backend"
RedfishBackendVar is the variable an operator sets -- in the inventory, in a play's vars or with -e -- to choose the backend of the redfish_info, redfish_command and redfish_config modules: "redfishtool" (the default: DMTF's redfishtool run on the target, so the request leaves from the target's network, as in real Ansible) or "go-redfish" (go-redfish in this process, so the request leaves from the control node).
The engine hands it to those modules as modules.RedfishBackendKey, the way it hands every module _ansible_diff. A variable is the operator's channel because real Ansible ignores a variable it does not know: a playbook that sets it still runs there. A task argument would not -- real refuses an argument outside the module's argument_spec.
Variables ¶
This section is empty.
Functions ¶
func AdHocHostVars ¶ added in v0.139.0
AdHocHostVars returns the variables an ad-hoc module invocation templates its arguments against, for one host out of the matched set.
It lives here, beside the play path's own construction, because the alternative is a second place that decides which variables exist — and two such places drift. `ansible -m debug -a 'msg={{ x }}'` has to resolve x the way a play would, and everything below was measured against real ansible-core 2.21.4 with exactly that command:
inventory_hostname "h1" inventory_hostname_short "h1" group_names ["web"] groups.web | length 2 hostvars["h2"].wv "from-web-group" wv "from-web-group" (a group_vars value) ansible_play_hosts|length 1 (the MATCHED hosts) inventory_dir the inventory's own directory playbook_dir the WORKING directory
The last two are not the same thing, which an inventory in a subdirectory shows: `-i sub/inv2` gives inventory_dir .../sub and playbook_dir the cwd. There is no playbook, so real uses the cwd.
func ConfigFilePath ¶ added in v0.4.1
func ConfigFilePath() string
ConfigFilePath returns the ansible.cfg go-ansible would read from — see findConfigFile — or "" if none of the usual locations has one. go-ansible/cli's ansible-config uses this for `view` and to report each setting's real origin (env var / config file / compiled default) in `dump`, rather than guessing from whether the resolved value merely differs from the default.
func ConfigFileValueForEnv ¶ added in v0.4.1
ConfigFileValueForEnv reports whether the ansible.cfg go-ansible would read from actually sets the [defaults] key matching envVar (e.g. "ANSIBLE_REMOTE_USER" -> "remote_user") — go-ansible/cli's ansible-config dump uses this to report a setting's real origin rather than guessing "cfg" just because some config file happens to exist, whether or not it sets that particular key.
func DefaultConnect ¶
func DefaultConnect(ctx context.Context, hostName string, hostVars map[string]any) (remoteexec.Connection, error)
DefaultConnect implements Ansible's connection-variable conventions: ansible_connection ("local" or "ssh", default "ssh" — "smart" is treated as ssh, this package has no separate paramiko/openssh split to be smart about), ansible_host, ansible_port (default 22), ansible_user, ansible_password / ansible_ssh_pass, ansible_ssh_private_key_file, ansible_host_key_checking, ansible_ssh_timeout. ansible_ssh_common_args is not implemented (OpenSSH-specific flags have no equivalent in a Go SSH client). "localhost"/"127.0.0.1" (by hostName, unless ansible_connection overrides it) use Local.
Three of these settings — remote_user, host_key_checking, timeout — match real Ansible's own config precedence: an inventory/host var wins if set, otherwise an ANSIBLE_* environment variable if set, otherwise ansible.cfg's [defaults] section (see configFileValue) if it sets the matching key, otherwise the compiled-in default below. (forks is a fourth setting on the same precedence, minus the host-var layer — see Engine.Forks/ConfigDefaults — since it's a global concurrency cap, not a per-host connection detail, so it doesn't belong in this function's own resolution chain.) These four settings are the full extent of this port's ansible.cfg support — no other section or key is read at all (a real, stated gap — see go-ansible/cli's ansible-config, which reports exactly this precedence and these four settings, nothing more). Unlike real Ansible's lenient boolean parsing (yes/no/on/off/1/0/true/false, case-insensitive), ANSIBLE_HOST_KEY_CHECKING here is parsed with Go's strconv.ParseBool (true/false/1/0/t/f, case-sensitive on the word forms) — an invalid value falls back to the compiled-in default rather than erroring, matching how an unset var behaves.
func DisplayName ¶ added in v0.34.0
DisplayName is the name Ansible shows for a task, in a run-time banner and in --list-tasks alike: the task's own name, or its module when it has none, prefixed with the role it came from — "myrole : the task", with spaces around the colon.
Exported because the banner and the listing must agree: a --list-tasks that named tasks differently from the run it describes would be worse than none.
func ParseModuleArgs ¶ added in v0.138.0
ParseModuleArgs turns an ad-hoc `-a` argument string into a module's arguments, the way real's ansible-adhoc does it.
It exists because this package already carries the faithful port of real's parse_kv/split_args — quote state, nested {{ }} and {% %} blocks, escaped equals, _raw_params — and the ad-hoc path needs exactly that. cli/internal/adhoc had its own strings.Fields version, which could not see quotes or Jinja blocks and SILENTLY DROPPED any token without an equals sign, so `-a 'msg=hello world'` ran with msg="hello" and `-a 'msg={{ v }}'` ran with msg="{{".
Two lists, and they are not the same list: freeformActions is real's MODULE_REQUIRE_ARGS (command, raw, script, shell, win_command, win_shell), which decides whether a k=v is an OPTION or part of the free-form text; rawParamModules is real's wider RAW_PARAM_MODULES, which decides whether a module may receive _raw_params at all. Reading check_raw off the wrong one would make `set_fact a=1` a raw param.
A JSON object is tried first, as real's ad-hoc does. Where real differs: on a string that merely LOOKS like JSON, `-a '{not json}'`, real raises and exits 250 with "Unexpected Exception". That is a traceback, not a behaviour to match, so this falls through to the k=v parser — which for most modules then reports the same raw-params refusal real would have given for any other unparseable argument.
func TagsSelect ¶ added in v0.31.0
TagsSelect reports whether a task carrying these effective tags is selected by the given --tags and --skip-tags lists. It is the same rule the engine applies when deciding what to run, exported because ansible-playbook's --list-tasks and --list-tags must show exactly what a run would do — answering that question twice, in two places, is how the two drift apart.
effective is a task's tags AFTER its play's and blocks' have been pushed down, which is what Parse already stores on Task.Tags. An empty run list means "all", which is what excludes a task tagged never; see tagsMatch for the full algorithm and where it comes from.
Types ¶
type BaseCallback ¶ added in v0.8.0
type BaseCallback struct{}
BaseCallback implements every Callback hook as a no-op. Embed it in a callback that only cares about some of them, matching CallbackBase's own all-no-op defaults.
func (BaseCallback) OnPlayStart ¶ added in v0.8.0
func (BaseCallback) OnPlayStart(Play, []string)
func (BaseCallback) OnStats ¶ added in v0.8.0
func (BaseCallback) OnStats(*RunResult)
func (BaseCallback) OnTaskResult ¶ added in v0.8.0
func (BaseCallback) OnTaskResult(Result)
func (BaseCallback) OnTaskRetry ¶ added in v0.23.0
func (BaseCallback) OnTaskRetry(Result, int)
type Callback ¶ added in v0.8.0
type Callback interface {
// OnPlayStart is raised once per BATCH of a play, with the hosts
// that batch will run against — real Ansible's
// v2_playbook_on_play_start. A play without serial: has exactly one
// batch containing every matched host, so this is once per play in
// the common case; a play WITH serial: raises it once per batch,
// which is what makes batch boundaries visible in the output, as
// they are in real Ansible.
//
// hosts is empty when the play's pattern matched nothing. Real
// Ansible still banners such a play and then says "skipping: no
// hosts matched", so a mistyped pattern does not read as a
// successful empty run.
OnPlayStart(play Play, hosts []string)
// OnTaskResult is raised for every task result on every host, one
// per loop iteration when a task loops. It covers what real Ansible
// splits across v2_runner_on_ok/failed/skipped, since Result already
// carries which of those it is.
OnTaskResult(r Result)
// OnTaskRetry is raised after each failed attempt of a task with
// until:/retries: that is going to be tried again — real Ansible's
// v2_runner_retry. left is how many retries remain AFTER this one,
// counting down to zero on the last.
//
// Without it a long retry loop is indistinguishable from a hang:
// real Ansible says "FAILED - RETRYING: [h1]: name (2 retries
// left)." after each attempt, and this port said nothing at all.
OnTaskRetry(r Result, left int)
// OnStats is raised once at the end of a RunPlaybook call, whether
// or not it returned an error — real Ansible's
// v2_playbook_on_stats, the PLAY RECAP hook.
OnStats(rr *RunResult)
}
Callback is a reporting plugin: it observes a run as it happens without influencing it, matching real Ansible's own callback plugin contract (ansible.plugins.callback.CallbackBase and its v2_* hooks). An Engine carries a list of them (Engine.Callbacks), the way real Ansible loads one stdout-type callback plus any number of notification-type ones at the same time.
Every hook is called synchronously from whichever goroutine reached it, so OnTaskResult in particular arrives concurrently from several host goroutines at once. An implementation that keeps state or writes to a shared stream must serialize itself — DefaultCallback does. A hook must not block or panic.
Embed BaseCallback to implement only the hooks you care about, the way a real callback plugin overrides only the v2_* methods it needs.
This port has three hooks where real Ansible has 24, because a hook nothing in this port can trigger, and nothing can consume, would be an empty promise. Two absences worth naming: real Ansible's v2_playbook_on_start produces nothing at default verbosity (confirmed from default.py — it prints only above -v), and this port has no verbosity concept to gate it on; and handler runs are indistinguishable from ordinary task runs here, so there is nothing to raise real Ansible's separate v2_playbook_on_handler_task_start from.
type CompatFinding ¶ added in v0.146.0
type CompatFinding struct {
// Line and Column are 1-based positions in the source, as yaml.v3
// reports them. Zero means the finding could not be located — a
// module name that only appears after a template expansion, say.
Line int
Column int
// Kind is "play keyword", "task keyword" or "module".
Kind string
// Name is the offending key or module name as the playbook spells it.
Name string
// Advice is what to write instead, in one sentence.
Advice string
}
CompatFinding is one construct in a playbook that no current Ansible will run — neither the reference nor this port — together with what to write instead.
It exists because the reference's own diagnosis names the symptom and not the cure. Measured against ansible-core 2.21.4, a play carrying a 2015-era `sudo: yes` exits 4 with "'sudo' is not a valid attribute for a Play", and the same key on a TASK exits 4 with "conflicting action statements: debug, sudo" — which does not even hint that `sudo` was ever a keyword. Users reach for an old virtualenv because the error tells them nothing else to try.
func CompatScan ¶ added in v0.146.0
func CompatScan(src []byte) ([]CompatFinding, error)
CompatScan reports every construct in a playbook source that no current Ansible will run, and what to write instead.
It works on sources that do NOT parse, which is the whole point: a playbook carrying `sudo:` fails to parse in the reference and here alike, so a report that needed a parsed playbook would have nothing to say in exactly the case it is for. Keyword findings come from a tolerant walk of the YAML; module findings are added only when the source does parse, since resolving a module name needs the play structure.
A nil error with no findings means the scan ran and found nothing. An error means the source is not YAML at all.
func CompatScanFile ¶ added in v0.146.0
func CompatScanFile(path, vaultPassword string) ([]CompatFinding, error)
CompatScanFile is CompatScan on the playbook at path, decrypting it first when it is vault-encrypted. An empty password behaves like ParseFile.
It exists because the CLI has a path, not bytes, and a vault-encrypted playbook is exactly as likely to be an old one: reading it with os.ReadFile would hand the scan a header line and a wall of base64, and the report would be "this is not YAML" for a playbook that is.
func (CompatFinding) String ¶ added in v0.146.0
func (f CompatFinding) String() string
type ConfigSetting ¶ added in v0.2.7
type ConfigSetting struct {
Name string
EnvVar string
IniSection string
IniKey string
Type string
Description string
VersionAdded string
Default string
Current string
Source string
}
ConfigSetting is one entry of ConfigDefaults' report.
Name is real Ansible's own canonical name for the setting -- DEFAULT_FORKS rather than forks -- because that is what `ansible-config dump` prints and what a person greps its output for. The ANSIBLE_* variable and the ini key are the two ways to set it.
Default and Current are rendered the way real renders them, which is PYTHON's repr and not Go's: True, False, None, a bare integer, a bare string. Source says where Current came from, in real's own spelling: "default", "env: ANSIBLE_X", or the path of the ini file.
Description is this port's OWN wording. Real's descriptions are GPL-licensed prose and these repositories are BSD-licensed, so copying them across would import a licence rather than a fact -- the names, variables, keys, types and defaults are interface facts and are matched exactly; the prose is not and cannot be.
func ConfigDefaults ¶ added in v0.2.7
func ConfigDefaults() []ConfigSetting
ConfigDefaults reports every setting this package honors from the environment and ansible.cfg's [defaults] section — go-ansible/cli's ansible-config is a thin printer over this.
It used to list four settings while the port honored seven: a person could not discover ANSIBLE_FORCE_COLOR, ANSIBLE_NOCOLOR or ANSIBLE_ALLOW_BROKEN_CONDITIONALS from `ansible-config` at all, though all three change what a run does.
Real lists 219. The ones missing here are missing because this port does not honor them, and listing a setting that changes nothing would be worse than its absence.
type Connector ¶
type Connector func(ctx context.Context, hostName string, hostVars map[string]any) (remoteexec.Connection, error)
Connector dials a connection to a host, given its name and fully merged variables (before task-level rendering — this only needs the ansible_* connection variables, which are ordinary inventory/group vars).
type DefaultCallback ¶ added in v0.8.0
type DefaultCallback struct {
BaseCallback
// Verbosity is -v's count: 0 for none, 1 for -v, and so on. At 1 or
// above an ok or changed line carries the whole result, which is
// what real's -v adds -- measured:
//
// changed: [localhost]
// changed: [localhost] => {"changed": true, "cmd": ["echo", …
//
// in the COMPACT single-line form, the same one a `fatal:` line
// uses, not the pretty 4-space block. A module that dumps at every
// verbosity (debug) keeps its pretty block; the two coexist in real
// at -v, and that was measured too.
//
// ⚠ What a higher level adds is NOT implemented, and is not faked
// by treating -vv as -v: real's -vv prefixes "task path: <file>:
// <line>", which needs source positions this port's parser does not
// keep (it unmarshals into []map[string]any), and -vvv adds
// connection tracing. The CLI says so in its own -h rather than
// letting a reader infer that nothing more exists.
Verbosity int
// Columns is the width banners pad out to with stars. Zero means
// real's own non-terminal value, 79 -- see banner. A caller writing
// to a terminal sets max(79, width-1), which is what real does.
Columns int
// contains filtered or unexported fields
}
DefaultCallback prints a run the way ansible-playbook prints it to a terminal — PLAY and TASK banners, a colored per-host line for every result, and a PLAY RECAP — and is this port's equivalent of real Ansible's own ansible.builtin.default stdout callback.
Its banners are not padded out with asterisks the way real Ansible's Display.banner pads them to the terminal width; that is a cosmetic difference this port has always had, named here rather than left to be discovered.
func NewDefaultCallback ¶ added in v0.8.0
func NewDefaultCallback(w io.Writer, color bool) *DefaultCallback
NewDefaultCallback returns a DefaultCallback writing to w, with ANSI color escapes when color is true.
func (*DefaultCallback) OnPlayStart ¶ added in v0.8.0
func (c *DefaultCallback) OnPlayStart(play Play, hosts []string)
func (*DefaultCallback) OnStats ¶ added in v0.8.0
func (c *DefaultCallback) OnStats(rr *RunResult)
func (*DefaultCallback) OnTaskResult ¶ added in v0.8.0
func (c *DefaultCallback) OnTaskResult(r Result)
func (*DefaultCallback) OnTaskRetry ¶ added in v0.23.0
func (c *DefaultCallback) OnTaskRetry(r Result, left int)
OnTaskRetry prints real Ansible's own retry line, verbatim from default.py's v2_runner_retry — including its unpluralised "1 retries left" and the trailing full stop. An unnamed task is named after its module, the same fallback the task banner uses.
type Engine ¶
type Engine struct {
Inventory *inventory.Inventory
Modules *modules.Registry
Template *template.Engine
ExtraVars map[string]any
Connect Connector
// BaseDir resolves include_vars' file argument at run time (every
// other file-referencing directive — vars_files, roles,
// include_tasks/import_tasks, include_role/import_role — resolves
// at parse time via ParseFile's directory instead). Defaults to "."
// when unset, matching Parse.
BaseDir string
// RunTags/SkipTags filter which tasks execute, matching
// ansible-playbook's --tags/--skip-tags: a task runs if its
// effective tag set (its own tags unioned with every enclosing
// block's and the play's, computed once at parse time — see
// propagateTags) intersects RunTags, or RunTags is empty, or the
// task carries the "always" tag; and does not intersect SkipTags.
// Filtered-out tasks are reported Skipped (real Ansible omits them
// from output entirely — this port reports them instead, for
// visibility). Tag filtering does not apply to handlers.
RunTags []string
SkipTags []string
// OnResult, if set, is called synchronously as each task result is
// produced (from whichever goroutine ran that host's task) — for
// live progress reporting. It must not block or panic; callers
// wanting ordering should serialize themselves. It is the one-hook
// shorthand for a caller that only wants results; a caller wanting
// play and recap events too installs a Callback instead.
OnResult func(Result)
// Callbacks are reporting plugins observing the run as it happens —
// this port's equivalent of real Ansible's own callback plugins, and
// a list for the same reason real Ansible loads one stdout callback
// alongside any number of notification ones. See Callback for the
// concurrency contract every hook is held to.
Callbacks []Callback
// Warn reports a non-fatal diagnostic about the run's inputs — a
// host pattern that matched nothing, for one. New installs a Warner
// writing real Ansible's "[WARNING]: " lines to stderr; a caller
// that already has one (go-ansible/cli builds the Warner it uses for
// its own inventory warnings) should assign THAT one here, so the
// whole process shares a single deduplication set the way real's one
// Display singleton does.
//
// A nil Warn is silent, not a panic.
Warn Warner
// Forks caps how many hosts run concurrently at once — connecting/
// gathering facts, and each task/handler fan-out (runSingleTask,
// runFree) all respect it — matching real Ansible's own forks
// setting (default 5; New sets this field to 5 for the same
// reason). 0 or negative means unlimited concurrency, which was
// this port's only behavior before Forks existed; New's default
// changes that for anyone constructing an Engine the normal way,
// but a caller that explicitly wants the old unbounded behavior can
// still set Forks to 0 after New returns.
Forks int
// CheckMode runs the playbook without changing anything —
// ansible-playbook's --check. A module that honours a dry run is told
// so and reports what it WOULD do; one that does not is skipped
// rather than run, which is what real Ansible does and what keeps a
// dry run safe while modules gain support one at a time.
CheckMode bool
// Limit restricts every play to hosts matching this pattern as well
// as their own — ansible-playbook's --limit. It takes the same
// pattern language as a play's hosts:, so "web:!web3" and "@file"
// style subsets work the same way, and it INTERSECTS rather than
// replaces: a play already narrower than the limit stays narrow.
//
// A limit that leaves the whole inventory with nothing to target is
// an error in real Ansible rather than a silent no-op — but that
// check belongs to the CLI, which makes it ONCE against "all"
// before any play runs (ansible/cli/__init__.py get_host_list).
// That is why a play whose own hosts: matches nothing is not an
// error while a --limit matching nothing is.
Limit string
// StartAtTask skips every task until one whose NAME matches, then
// runs from there on — ansible-playbook's --start-at-task. The
// match is exact OR a shell glob (real Ansible uses fnmatch) and is
// case-sensitive, so "two" and "tw*" and "*wo" all find a task
// named two while "tw" and "TWO" do not. It is tried against a
// task's own name and against the "role : name" form a role task
// displays, both of which real Ansible tries.
//
// Once a task has matched, the skipping stops for the REST OF THE
// RUN — across later plays, and across later playbooks run through
// the same Engine. That is what makes --start-at-task resume a
// multi-play run at a point rather than re-skipping inside every
// play.
//
// A skipped task produces no result at all: no banner, no
// "skipping:" line, nothing in the recap, exactly as a task
// excluded by tags does.
StartAtTask string
// ForceHandlers runs a host's notified handlers even when that host
// has already failed — ansible-playbook's --force-handlers.
// Normally a failed host runs nothing further, handlers included,
// which can leave a service stopped because the handler that would
// have restarted it never ran.
ForceHandlers bool
// AllowBrokenConditionals permits a when:/until:/changed_when:
// whose result is not a boolean, applying ordinary truthiness
// instead of refusing — real Ansible's ALLOW_BROKEN_CONDITIONALS,
// which defaults to off there too and which upstream plans to
// remove in 2.23.
//
// A playbook that needs it is a playbook real ansible-core also
// refuses, so this exists to unblock a migration rather than to be
// left on.
AllowBrokenConditionals bool
// DiffMode makes modules report what they changed —
// ansible-playbook's --diff. A module that supports it returns the
// before and after contents, which the callbacks render as a unified
// diff; one that does not simply reports nothing extra, exactly as
// in real Ansible, so turning it on is never destructive and never
// fails a run.
//
// It composes with CheckMode: --diff --check shows the diff of a
// change that is deliberately not made.
DiffMode bool
// Prompt implements vars_prompt's actual interactive prompting:
// given the fully-formatted message (already combining the prompt
// text and "[default]" the way real Ansible's own do_var_prompt
// does) and whether the input should be hidden, it returns what the
// user entered. New's default (defaultPrompt) is a plain
// bufio-over-os.Stdin read with no terminal awareness at all — it
// works the same whether stdin is a real terminal or a pipe (never
// hides input, and never detects a non-interactive session the way
// real Ansible does to skip prompting and warn instead), which
// matches a raw library caller or a piped/test invocation but not
// real Ansible's actual interactive behavior. go-ansible/cli's
// ansible-playbook overrides this with a real, terminal-aware
// implementation (golang.org/x/term) for actual interactive use.
Prompt func(msg string, private bool) (string, error)
// VaultPassword decrypts a vault-encrypted file loaded at RUN time —
// today that means include_vars. Files pulled in while parsing (the
// playbook, vars_files, a role's own files) take their password from
// ParseFileWithVault instead, since parsing happens before an Engine
// exists.
VaultPassword string
// contains filtered or unexported fields
}
Engine runs playbooks against an inventory. The zero value is not usable — use New.
func New ¶
New returns an Engine with the built-in module registry, a fresh template engine, and DefaultConnect.
func (*Engine) RunPlaybook ¶
RunPlaybook runs every play in pb in order.
func (*Engine) UnresolvedModules ¶ added in v0.124.0
func (e *Engine) UnresolvedModules(pb Playbook) []UnresolvedModule
UnresolvedModules reports every task in pb whose module name neither this engine's registry nor its own directive set can run.
⚠ This exists because the port diverged from real in a way that can CHANGE A MACHINE. Real refuses the whole playbook before touching any host -- measured: a playbook whose SECOND task names a bad module leaves the first task's `touch` file uncreated, and exits 4. This port ran every preceding task and failed only when it reached the bad one, so a typo in task 5 applied tasks 1 through 4 for real. (The first probe for this looked for the first task's output in real's stdout and found it -- real's error message QUOTES the offending source lines, including the neighbouring one. The file witness is what settled it.)
Roles need no special handling: parseRoles resolves a play's roles: list into synthetic block tasks at PARSE time, so the walk below reaches them. What it does NOT reach is a file pulled in at run time by include_tasks, whose target is read only when the task executes. Real refuses those too; this port still fails them where they run.
A templated module name is left alone: `action: "{{ mod }}"` is resolved later, and real accepts it (measured, exit 0).
type HostSummary ¶
type HostSummary struct {
Ok, Changed, Failed, Skipped int
// Unreachable, Rescued and Ignored are real Ansible's own further
// recap columns. Without them a rescued or ignored failure has
// nowhere to go but "failed", which is what this port used to do —
// reporting failures for a run real Ansible calls clean.
Unreachable, Rescued, Ignored int
}
Summary counts changed/failed/skipped/ok results across the whole run, keyed by host — Ansible's PLAY RECAP.
type Play ¶
type Play struct {
Name string
Hosts string
GatherFacts bool // default true
// FactPath is real's fact_path: the directory whose *.fact files
// become ansible_local. Honoured through facts.Options.
FactPath string
// ForceHandlers is real's force_handlers, and it is a POINTER
// because the keyword overrides the --force-handlers flag in BOTH
// directions: measured, `force_handlers: false` with
// --force-handlers on the command line does not run the handler.
// A plain bool could not tell "false" from "not set".
ForceHandlers *bool
Become bool
BecomeUser string
BecomeMethod string
BecomeExe string // become_exe: the escalation program to run
BecomeFlags string // become_flags: REPLACES the method's own default flags
Vars map[string]any
VarsFiles []string // paths, resolved relative to the playbook's directory
Tasks []Task
Handlers []Task
Tags []string
// Serial is the rolling-update batch sizes. Each entry is either a
// plain count ("2") or a percentage of the play's TOTAL host count
// ("50%"); a list gives successive batch sizes, whose last entry
// repeats until every host has run. Empty means "all hosts at
// once", the linear strategy's default.
//
// Real Ansible's own `serial` is a list attribute, so a YAML scalar
// is normalised into a one-element list here too — `serial: 2` and
// `serial: [2]` are the same play.
Serial []string
// Environment is added to the environment of every command the play
// runs. A task's own environment: is merged over it, key by key.
Environment map[string]any
// ModuleDefaults are per-module argument defaults, keyed by module
// name: every task in the play that runs that module gets them
// underneath its own arguments. A task or block may set its own,
// which REPLACES the play's entry for that module outright rather
// than merging key by key — measured against real ansible-core
// 2.21.4, where a play-level `copy: {mode, content}` plus a
// task-level `copy: {mode}` loses the content and the task fails
// "src (or content) is required".
ModuleDefaults map[string]map[string]any
// IgnoreUnreachable keeps a host in the play when it cannot be
// reached, instead of dropping it: the result still prints
// UNREACHABLE!, the recap counts it ok+ignored rather than
// unreachable, and the next task tries to connect again. A task
// may override it either way.
IgnoreUnreachable bool
// Order is how the play's hosts are sequenced: "inventory" (the
// default), "sorted", "reverse_sorted", "reverse_inventory" or
// "shuffle".
Order string
// CheckMode forces this play into (or out of) a dry run, whatever
// the --check flag says. Nil means "follow the flag" — which is NOT
// the same as false, since false forces a REAL run under --check.
CheckMode *bool
// Connection, RemoteUser and Port are the play's connection
// defaults — ansible's connection:, remote_user: and port:. Each is
// overridden by the matching host variable (ansible_connection,
// ansible_user, ansible_port), which is the precedence real Ansible
// applies: measured with a host var of ssh against a play keyword
// of local, where the HOST VAR won.
Connection string
RemoteUser string
Port int
// AnyErrorsFatal stops the WHOLE play the moment any host fails,
// rather than carrying on with the hosts that are still healthy.
AnyErrorsFatal bool
// MaxFailPercentage stops the play once more than this percentage
// of the current batch has failed. Nil means no limit — which is
// NOT the same as 0, where a single failure stops everything.
MaxFailPercentage *float64
Roles []RoleRef
// Strategy is "linear" (the default: every host finishes task N
// before any host starts task N+1) or "free" (each host runs its
// entire task list, and its own notified handlers, independently —
// a slow host never holds back a fast one). Any other named
// strategy real Ansible supports (debug, host_pinned, or a
// strategy plugin) is rejected at parse time rather than silently
// treated as linear.
Strategy string
// VarsPrompt, resolved once per play (not per host) before its
// tasks run — see Engine.applyVarsPrompt — into an ordinary play
// var, same scope as Vars. Real Ansible only accepts a list of
// maps here, never a bare-string shorthand (confirmed from
// ansible-core's own Play._load_vars_prompt/preprocess_vars: an
// item that isn't a mapping raises a parse error there too).
VarsPrompt []VarPrompt
}
Play runs a set of tasks against a pattern of inventory hosts.
func (Play) ListedTasks ¶ added in v0.31.0
ListedTasks returns the tasks ansible-playbook's --list-tasks shows for this play, in order: every task that runs a module, descending into a block's block: but NOT into its rescue: or always:.
That asymmetry is real Ansible's own, measured rather than assumed — a block's rescue and always tasks do not appear in the listing even though they are part of the play and will run. Role tasks DO appear, because a play's roles: are expanded into its task list at parse time; Task.RoleDir names the role each came from.
Tags on the returned tasks are already the EFFECTIVE ones, since parsing pushes a play's and a block's tags down into the tasks they contain.
type PlayResult ¶
type PlayResult struct {
Play string
Results []Result
// Rescued counts, per host, the blocks whose rescue recovered a
// failure. It is not derivable from Results: rescuing is a property
// of a BLOCK, and the failing task inside it looks the same either
// way. Real Ansible counts those under "rescued" and not "failed".
Rescued map[string]int
// contains filtered or unexported fields
}
PlayResult aggregates every Result from one play, in the order record was called — not necessarily task-list order, since the engine runs one goroutine per active host and every host's goroutine calls record on the same *PlayResult concurrently. mu is a pointer (not an embedded sync.Mutex) specifically so a PlayResult can still be copied by value — as RunPlaybook does, appending *pr into RunResult.Plays — without go vet's copylocks check firing; every copy keeps pointing at the one real mutex.
type Playbook ¶
type Playbook []Play
Playbook is an ordered list of plays, as ansible-playbook reads it.
func Parse ¶
Parse parses a playbook YAML document (a top-level list of plays). File-referencing directives (vars_files, roles, include_tasks, import_tasks, include_role, import_role) resolve their paths relative to the current working directory — use ParseFile when the playbook lives elsewhere and its includes should resolve relative to it.
func ParseFile ¶ added in v0.2.0
ParseFile reads and parses the playbook at path, resolving every file-referencing directive relative to path's directory (matching ansible-playbook, which resolves roles/ and included files relative to the playbook file, not the current working directory).
func ParseFileWithVault ¶ added in v0.14.0
ParseFileWithVault is ParseFile with a vault password, so the playbook or any file it pulls in — a vars_files target, a role's own defaults/vars/tasks — may be vault-encrypted. An empty password behaves exactly like ParseFile.
type Result ¶
type Result struct {
Host string
// TaskID is the ID of the task INSTANCE this result came from. The
// callback banners on it rather than on Task, because two unnamed
// tasks of the same module display the same name and real banners
// each one. Zero means unnumbered, and the callback then falls back
// to the displayed name.
TaskID int
Task string
Module string
Changed bool
Failed bool
Skipped bool
// ArgsFailed marks a failure that happened BEFORE the module ran,
// while finalizing its arguments. Such a result has no module
// result dict behind it, so it carries none of the keys one would
// have — including the item/ansible_loop_var an iteration's own
// failure shows.
ArgsFailed bool
// DisplayOnly marks a line that is printed but counts toward
// nothing in the recap: real closes a loop whose arguments would
// not finalize with a task-level summary AFTER the per-item lines,
// and counts the task once, not twice.
DisplayOnly bool
// LoopVar is the name the loop bound its item to — "item" unless
// loop_control.loop_var said otherwise. A failing iteration's
// printed result carries it, as ansible_loop_var.
LoopVar string
// ItemLabel is what a looping task prints in its `(item=...)`:
// loop_control.label when the task set one, and the item itself
// otherwise. Kept apart from Item because Item is what register:
// and the result dict carry, and a label only changes the
// PRINTING.
ItemLabel any
// Included is the file a dynamic include_tasks pulled in, and is
// set only on the announcement result real Ansible prints for one:
// "included: <path> for <host>".
Included string
// BannerOnly marks a result that exists only to banner its task:
// real Ansible's meta: fires the task-start callback and no runner
// callback at all, so it prints a TASK header with no line under
// it and counts toward nothing in the recap.
BannerOnly bool
// Ignored marks a failure the task's own ignore_errors swallowed.
// Real Ansible counts one of these under "ignored" AND under "ok",
// not under "failed" — a run whose every failure was ignored reports
// failed=0.
Ignored bool
// Unreachable marks a host that could not be connected to at all.
// Real Ansible gives it its own recap column, separate from a task
// that ran and failed.
Unreachable bool
Msg string
Extra map[string]any
// Diffs is what the task changed, present only under
// Engine.DiffMode and only for a module that reports one. A
// callback renders them; nothing in the engine reads them.
Diffs []modules.Diff
// Item is the loop item this result is for, and Looped says the
// task looped at all — separate, because an item may legitimately
// be nil. Real Ansible prints the item on the result line, and
// counts a looped task ONCE in the recap however many iterations
// it ran.
Item any
Looped bool
// NoLog marks a result whose task set no_log: true. A callback must
// print nothing from it beyond the outcome and the host: real
// Ansible replaces the whole result with a single `censored` key,
// keeping only `changed`.
//
// It matters most on FAILURE, which is exactly when a result is
// dumped in full — a task handling a credential would otherwise
// leak it at the worst moment.
NoLog bool
// Role is the name of the role this task came from, empty for a
// task written directly in a playbook. Real Ansible banners such a
// task "TASK [myrole : the task]"; see DisplayName.
Role string
// Handler marks a result produced by a handler rather than an
// ordinary task. Real Ansible banners those differently —
// "RUNNING HANDLER [restart nginx]" rather than "TASK [...]" — which
// is how a reader tells a handler run from a task that happens to
// share its name.
Handler bool
// Delegate is the host a delegate_to task actually ran against,
// already templated. Empty when the task ran on Host itself — and
// also empty for a task that was skipped, since a skipped task
// never connects anywhere. Real Ansible reports the pair as
// "ok: [web1 -> deploy1]".
Delegate string
}
Result is one task's outcome on one host (one per loop iteration when a task loops).
type RoleRef ¶ added in v0.2.0
type RoleRef struct {
Name string
Vars map[string]any
// When and Tags are the `when:`/`tags:` an entry in `roles:` may
// carry. Both were parsed and thrown away before #192.
When string
Tags []string
}
RoleRef is one entry of a play's roles: list.
type RunResult ¶
type RunResult struct {
Plays []PlayResult
}
RunResult aggregates every play's results, in playbook order.
func (*RunResult) Failed ¶
Failed reports whether the run ended with a real failure — the question ansible-playbook's exit code asks. It is the host's FINAL state, not the history: a failure the task's own ignore_errors swallowed does not count, and neither does one a block's rescue recovered. Real ansible-playbook exits 0 for a run whose only failures were ignored or rescued, and this port used to exit 2.
func (*RunResult) Summary ¶
func (rr *RunResult) Summary() map[string]*HostSummary
func (*RunResult) Unreachable ¶ added in v0.51.0
Unreachable reports whether any host ended the run unreachable — one whose ignore_unreachable said to carry on does NOT count, since real Ansible files it under ok/ignored instead.
It is separate from Failed because real ansible-playbook's exit code distinguishes them, and unreachable WINS: 4 if any host was unreachable, else 2 if any failed, else 0 (ansible's own StrategyBase._process_pending_results tail, and measured — a run with one failed host and one unreachable host exits 4, not 2 and not 6).
type Task ¶
type Task struct {
// ID identifies this task INSTANCE within its play, which is not
// the same thing as its name: two unnamed `- debug:` tasks in a row
// both display as "debug", and real banners each of them. Numbered
// after parsing, so a block's children are numbered too.
ID int
Name string
Module string
Args map[string]any
When string // Jinja2 expression, already normalized from a string or []string
Loop any // a literal list, or a "{{ expr }}" string rendered at run time
// LoopWith names the lookup plugin a with_<name>: key asked for,
// empty for a plain loop:. Real routes both through the same
// place — with_items IS the items lookup — and so does this.
LoopWith string
LoopVar string // default "item"
IndexVar string // loop_control.index_var — unset means no index variable
// LoopPause is loop_control.pause — seconds to wait between
// iterations. Reported in ansible_failed_task, where real carries
// it as a float.
LoopPause float64
// LoopLabel is loop_control.label — what real prints in the
// `(item=...)` of each iteration INSTEAD of the item itself, so a
// loop over big dicts stays readable. It is a template, rendered
// per item.
LoopLabel string
// LoopExtended is loop_control.extended: it publishes the
// ansible_loop dict to each iteration. Off by default, and real's
// ansible_loop is then UNDEFINED rather than empty -- measured.
LoopExtended bool
// LoopExtendedAllItems is loop_control.extended_allitems, which
// decides whether ansible_loop carries the whole item list. Real
// defaults it to TRUE, so it is a pointer: absent means true, and
// only an explicit false drops the key.
LoopExtendedAllItems *bool
// Throttle is the task-level throttle: keyword -- the most hosts
// that may run THIS task at once, however many forks the run has.
// Zero (and absent) mean no cap of its own.
Throttle int
// Timeout is the task-level timeout: keyword, in seconds. Real
// gives up on the task's action after that long, discards whatever
// it was doing and fails. Zero (and absent) mean no timeout, which
// is real's own default -- measured, `timeout: 0` lets a two-second
// sleep finish.
Timeout int
// LoopBreakWhen is loop_control.break_when, already normalized to
// one expression. It is evaluated AFTER each iteration, and when
// it holds the loop ends -- the iteration that triggered it has
// already run and reported, which is what makes break_when
// different from when:.
//
// A LIST of conditions is AND-ed, like every other Ansible
// conditional. Measured: break_when: ["item == 2", "item == 3"]
// never holds and all three items run, while
// ["item >= 2", "item is even"] stops after item 2.
LoopBreakWhen string
Register string
IgnoreErrors bool
// Diff is the task-level `diff:` keyword. It is a POINTER because
// it overrides --diff in BOTH directions -- measured: `diff: true`
// turns diff on for that task without the flag, and `diff: false`
// turns it off despite the flag -- so "unset" has to be a third
// state rather than false.
Diff *bool
ChangedWhen string
FailedWhen string
Tags []string
Become *bool // nil means "inherit the play's setting"
// Connection, RemoteUser and Port are this task's own
// connection:/remote_user:/port:. They were refused by name until
// the engine could change a connection mid-play; now that a task's
// variables decide which connection it gets, these are simply the
// keyword spelling of ansible_connection/ansible_user/ansible_port.
//
// Measured precedence, against ansible-core 2.21.4:
//
// host var > task keyword > play keyword
//
// A host with ansible_connection=ssh ignored `connection: local` on
// the task and went UNREACHABLE; a host with no connection variable
// ran LOCALLY under `connection: local` on the task beneath a play
// saying `connection: ssh`. The same ladder become: already uses.
Connection string
RemoteUser string
Port int
// Debugger is the task's `debugger:`. Only `never` is accepted --
// the one value that asks for nothing, since it turns off a
// debugger this port does not have. Every other value is refused at
// parse time.
//
// The tempting assumption is that the others are no-ops in a
// non-interactive run. They are NOT: measured against ansible-core
// 2.21.4 with stdin closed, `debugger: on_failed` on a failing task
// still prints its prompt --
//
// [h1] TASK: fails (debug)> User interrupted execution
//
// -- so it changes the transcript and the control flow, and
// accepting it would be the silent-ignore this list exists to avoid.
Debugger string
BecomeUser string
BecomeExe string
BecomeFlags string
Notify []string
// Listen are the notify TOPICS this handler answers to, on top of
// its own name. Only meaningful on a handler.
Listen []string
Vars map[string]any
DelegateTo string
// Until/Retries/Delay implement the task retry loop: real Ansible
// runs the task 1+Retries times (Retries nil, the "unset" state,
// means no retry loop at all UNLESS Until is non-empty, in which
// case real Ansible defaults Retries to 3 — mirrored in
// runTaskOnHost, not here, since it needs to distinguish "Retries
// explicitly 0" from "Retries unset"), re-checking Until (or, if
// Until is empty but Retries was explicitly set, "not failed")
// after each attempt and sleeping Delay seconds before the next one
// if it didn't pass. See runTaskOnHost's retry loop for the exact
// attempt-counting algorithm, including a real, deliberately
// reproduced quirk in ansible-core's own retry loop.
Until string
Retries *int
Delay float64
// RunOnce restricts execution to the first currently-active host in
// a runSingleTask call, broadcasting any Register result to every
// other active host afterward (so a later task on ANY host can
// still read it by bare name) — matching real Ansible's own
// run_once, including its result-sharing, verified against a real
// ansible-playbook run. A real, narrower limitation under strategy:
// free: each host there calls runSingleTask with itself as the only
// active host (see runFree), so there is no cross-host "first one"
// to restrict to — every host still runs its own copy. Real Ansible
// coordinates run_once across free's independent per-host lanes;
// this port does not, and says so here rather than silently
// re-running the task on every host without comment.
// RunOnce is tri-state, as it is there: nil means the playbook
// never mentioned it, which ansible_failed_task reports as null
// rather than false.
RunOnce *bool
// Async/Poll implement async:/poll: — see runTaskOnHost's async
// branch and modules.AsyncLaunch/AsyncCheck for the real mechanism
// and its one disclosed limitation (no active kill on timeout).
// Async <= 0 means synchronous, ordinary execution — the
// overwhelming majority of tasks. Only command/shell support
// Async > 0 at all: every other module's work happens as a
// sequence of calls from the control node, not one remote
// invocation that could be backgrounded on the target the way
// async requires — a task on any other module with Async > 0 fails
// loud rather than silently running synchronously and ignoring
// what was explicitly asked for. Poll nil means "unset": defaults
// to 15 seconds (real Ansible's own DEFAULT_POLL_INTERVAL) when
// Async > 0; Poll 0 is fire-and-forget (the task returns immediately
// once the job is launched, for a later task to check via
// async_status); Poll > 0 waits, checking every Poll seconds, until
// the job finishes or Async seconds pass (a timeout failure).
Async int
Poll *int
// RoleDefaults/RoleVars are set only on the synthetic block task
// produced for a roles: entry or include_role/import_role — the
// engine (Engine.pushRoleVars) merges them on top of the
// RoleDefaults/RoleVars layers' current content for the duration of
// the block, then restores the prior (pre-merge) content. Nesting
// (a role that itself includes another role) composes correctly to
// any depth this way: a variable the inner role doesn't define in
// its own defaults/main.yml or vars/main.yml still resolves to
// whatever the enclosing role(s) already had, matching real
// Ansible's behavior of keeping every currently active role's
// defaults/vars in scope at once.
RoleDefaults map[string]any
RoleVars map[string]any
// RoleVarsScoped limits RoleDefaults/RoleVars to this role's own
// block, unwinding them when it ends. True only for include_role,
// which is dynamic: real Ansible resolves it at run time and its
// variables leave scope with it. A roles: entry and import_role are
// both static — real Ansible injects their variables for the whole
// play, so they persist. Measured against real ansible-core 2.21.4
// by running include_role and import_role in isolation: after the
// former the role's vars read as undefined, after the latter they
// still resolve.
RoleVarsScoped bool
// IncludedFile is set on the synthetic block an include_tasks
// parses into, and holds the resolved path of the file it pulled
// in. Real Ansible announces a dynamic include — a banner plus
// "included: <path> for <host>", counted as ok in the recap — and
// announces nothing for a static import; this carries what that
// line needs.
IncludedFile string
// ArgsError is a refusal discovered while parsing the task's
// arguments that real only raises when the task RUNS. Kept as a
// message rather than an error so the playbook still parses: real
// runs the tasks before it, and skips this one entirely when its
// when: is false.
ArgsError string
// RoleDir is the directory of the role this task came from, empty
// for a task written directly in a playbook. A relative src: on a
// file-carrying module resolves against it — real Ansible looks in
// the role's own files/ (or templates/ for template) before
// anything else, which is what makes "src: hello.txt" work inside a
// role at all.
RoleDir string
// Environment is added to the environment of the command this task
// runs, merged over its play's — the task's entry wins on a key
// both set.
Environment map[string]any
// ModuleDefaults is this task's EFFECTIVE set of per-module
// argument defaults — its own, over any enclosing block's, over
// the play's, resolved once at parse time by
// propagateModuleDefaults. Applying it is argsWithDefaults's job.
ModuleDefaults map[string]map[string]any
// IgnoreUnreachable overrides the play's for this task; nil means
// inherit it. Real Ansible decides per TASK, which is what makes
// an ignored-unreachable ping followed by an ordinary command
// report UNREACHABLE twice and drop the host only on the second.
IgnoreUnreachable *bool
// CheckMode forces this task into (or out of) a dry run. Setting it
// FALSE is the useful case: real Ansible runs such a task for real
// even under --check, which is how a playbook reads state it needs
// in order to predict the rest.
CheckMode *bool
// AnyErrorsFatal stops the whole play when THIS task fails on any
// host, whatever the play's own setting.
AnyErrorsFatal bool
// NoLog hides this task's result. Real Ansible replaces the whole
// result with a single `censored` key, keeping only `changed`, so a
// task handling a credential cannot leak it through the callback —
// including when it FAILS, which is when a result is dumped in full.
NoLog bool
Block []Task
Rescue []Task
Always []Task
}
Task is one step of a play (or of a block's body/rescue/always). Module/Args are populated from whichever single non-reserved key the task's YAML mapping carried (e.g. `copy:` or `command:`) — empty for a block/meta task.
type UnresolvedModule ¶ added in v0.124.0
UnresolvedModule is one task naming something neither the registry nor the engine can run. Play and Task are for the message; a task with no name is reported by its module, as real does.
type UnresolvedModulesError ¶ added in v0.124.0
type UnresolvedModulesError struct {
Unresolved []UnresolvedModule
}
UnresolvedModulesError is what RunPlaybook returns instead of running a playbook that names a module nothing can satisfy. Callers that map errors to exit statuses can match it with errors.As: real Ansible treats this as a PARSE error (exit 4), not a task failure (exit 2), because no task ever runs.
func (*UnresolvedModulesError) Error ¶ added in v0.124.0
func (e *UnresolvedModulesError) Error() string
type VarPrompt ¶ added in v0.5.0
VarPrompt is one vars_prompt entry. Prompt defaults to Name when empty, Private defaults to true (confirmed from ansible-core's own playbook_executor.py: private = boolean(var.get("private", True)) — prompts hide input UNLESS private: false is explicit, the opposite of what the name alone might suggest). encrypt/salt/salt_size/unsafe (hashing the prompted value, and disabling template-escaping of it) are real ansible-core vars_prompt keys this port does not implement — accepted and parsed for shape compatibility, silently no-op'd rather than erroring on an unrecognized key, since a real playbook using only the common name/prompt/default/private/confirm subset (the overwhelming majority) should not need every knob wired to run.
type Warner ¶ added in v0.73.0
type Warner func(msg string)
Warner reports a non-fatal diagnostic — something the user should see, that does not stop the run. It is this port's equivalent of real Ansible's display.warning.
It is separate from Callback on purpose. A callback reports the PROGRESS of a run and writes to the run's own output stream; a warning is about the run's INPUTS (a pattern that matched nothing, an inventory that could not be read) and real writes it to stderr, so that a caller piping a playbook's output somewhere still sees it. Real makes the same split, between its callback plugins and the one Display singleton they all share.
func NewWarner ¶ added in v0.73.0
NewWarner returns a Warner that writes each message to w in real Ansible's own shape — the literal "[WARNING]: ", then the message, on one line — and writes each DISTINCT message at most once.
The deduplication is real's, not a convenience: display.warning keeps the set of warnings it has already issued, and a run that would warn the same thing repeatedly says it once. Measured against ansible-core 2.21.4 with a three-play playbook whose plays matched an empty inventory: "provided hosts list is empty" appeared once rather than three times, and two plays sharing a mistyped pattern produced one line for it, not two. Without this, a playbook with twenty plays would say the same thing twenty times where real says it once.
The returned Warner is safe for concurrent use, because a run warns from whichever goroutine noticed — and strategy: free has several.