modules

package module
v0.103.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 43 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

modules

Ansible module execution protocol plus the core module library.

Part of go-ansible — a pure-Go (CGO=0), functional-parity port of Ansible.

CI Go Reference License

Usage

reg := modules.Default() // pre-populated with the built-in module set

res, err := reg.Run(ctx, "copy", conn, map[string]any{
    "src": "app.conf", "dest": "/etc/app.conf", "mode": "0644",
})
if res.Failed {
    // res.Msg explains why
}

conn is a github.com/go-remoteexec/transport.Connection — local, SSH or WinRM. The WinRM one reaches a Windows host, though most modules here compose POSIX shell and so will not run against one; the ansible.windows family is not ported. Unlike real Ansible, a module here runs its logic on the control node and reaches the target only through the connection's Exec/Put/Fetch primitives — no Python, no script copied to the target. reg.Names() lists every registered module name; reg.Register adds or overrides one.

Which collection a module came from

Collection(name) answers "ansible.builtin", "ansible.posix" or "community.general", and FQCN(name) builds the name real ansible-doc prints — community.general.rocketchat, ansible.posix.synchronize.

It exists because a consumer printing a qualified name had no way to get it right, and the wrong name was worse than cosmetic: NormalizeName strips any known prefix, so ansible.builtin.rocketchat ran here and real Ansible rejects it. Our own ansible-doc was handing out a name that only works on us, and nothing local could tell you.

The three lists were measured on 2026-10-18 by intersecting Default().Names() with ansible-doc -l <collection> -t module from real ansible-core 2.21.4 — 62, 14 and 500 names, disjoint, their union exactly the registry. Both properties are asserted, so a module added without an entry fails the build rather than silently becoming ansible.builtin, which is how the old assumption survived 514 modules.

ansible.builtin has 71 modules; the nine missing here (add_host, group_by, meta and the import_*/include_* family) are playbook constructs rather than remote modules, and live in playbook — where real Ansible keeps them too.

Redfish: where the BMC request leaves from

redfish_command, redfish_config and redfish_info run DMTF's redfishtool on the target through the connection by default, so the request to the BMC leaves from the target's network, as it does in real Ansible (which runs the module on the target). That is unchanged.

An operator can instead ask for the in-process go-redfish client: the request then leaves from the control node, the connection is not used and redfishtool is not needed on the target. It is stated, never inferred from the connection. The switch is the key _goansible_redfish_backend: go-redfish (modules.RedfishBackendKey), which the engine passes in the module's args the way it passes _ansible_diff; its name is deliberately outside real Ansible's _ansible_* namespace. Any other value than redfishtool or go-redfish is refused. An engine that includes go-ansible/playbook#215 sets it from the variable goansible_redfish_backend (inventory, play vars or -e), which real Ansible ignores. Without that engine, the only way is a task argument, and a playbook using it is not portable: real Ansible refuses a parameter outside the module's argument_spec.

Both backends check the arguments the way real does, with real's messages: username and auth_token are mutually exclusive, username and password go together, and one of username or auth_token is required. baseuri is a host (host[:port]), since real builds https:// + baseuri; a value with a scheme is refused.

On that backend auth_token works (the default path refuses it, since redfishtool takes a token only on argv), every command of the three modules is implemented, validate_certs defaults to true and ca_path names the CA. The password and the token stay in this process's memory. Its results were compared with real ansible-core and community.general on the same mock BMC (redfish_interop_test.go; run with ansible on PATH and ANSIBLE_COLLECTIONS_PATH pointing at a community.general checkout; the test skips without them, and fails instead when ANSIBLE_REQUIRE is set); the rows where the two differ are listed, with the reason, in that file.

Security

A module here composes a shell command, so a value that reaches a command string reaches a shell. Three controls, all mechanical rather than careful:

  • Quoting. Every interpolated value goes through this package's shellQuote — 1 415 call sites in 624 non-test files on 2026-11-01, and 1 720 counting the tests. Being careful does not scale to that, and a missed site is indistinguishable from a deliberate one until somebody looks.

    The figures used to be quoted as "1 718 call sites across 620 non-test files", which paired the total including tests with the count of files excluding them — two measures of different populations read as one. They drift with every batch, so they are given with the thing that produced them rather than as a number to trust:

    go run ./countsites -dir . -literal 'shellQuote('
    
  • Credentials in the environment, via transport's ExecWithEnv, which is what real Ansible does with run_command's environ_update. Never a secret in argv, where ps shows it to every local user.

  • Credentials on stdin for the HTTP modules, which have no vendor CLI and so reach their API with curl on the target. The command is only curl -s -K - --max-time N -w …: the url, the headers, the body and any user = basic-auth pair travel through curl's config file on stdin. A webhook url often is the credential — rocketchat's token is two of its path segments — so this is not only about -u and -H. The test helper assertSecretsOffArgv carries its own control: each secret must appear on stdin, so it cannot pass on a module that simply never sent one.

Stdin keeps a credential out of argv; it does not make the value safe by itself, and v0.95.1 fixed the half that was missing. curl reads one option per physical line, and the function quoting values into that config escaped only backslash and double quote — its own comment said "no embedded newlines", which was true of the one caller it was written for and of none of the callers added since. A value carrying a newline therefore ended its directive and opened another: measured on curl 8.7.1, a url of file:///etc/hosts\nurl = file:///etc/passwd\n# makes curl perform two transfers, the second of a file the caller never named. The escape now covers all five sequences curl accepts inside quotes, a control character in a url, header, query parameter or basic-auth pair is refused before anything runs, and TestRealCurlDoesNotActOnAnInjectedDirective holds it against the real binary with its own neuter — it fails if the old escape stops leaking.

An audit of this library found one breach of each of the first two, both fixed in v0.80.0 and v0.80.1: async_status's jid was interpolated unquoted into an rm -rf, and keyring built its passwords into a two-statement command, where the shell cannot exec away and holds them in its argv. The port's remaining unavoidable exposures — macOS security's own argv, and two vendor CLIs with an irreducible token flag — are named, with the measurement behind each.

The full writeup, including the measured ps-visibility boundary and the three lessons that generalise beyond these two defects, is on the Security page.

Documentation

Overview

Package modules implements Ansible's module execution model: each module is a Go function that takes a target connection (github.com/go-remoteexec/transport) and a set of arguments (already Jinja2-rendered by the caller) and returns a Result — Ansible's changed/failed/msg triple plus any module-specific fields.

Unlike real Ansible, which copies a Python script to the target and runs it there, a module here runs its logic on the control node and reaches the target only through the Connection's Exec/Put/Fetch primitives. The observable behavior is the same (the target ends up in the same state); the difference is architectural, not behavioral, and it means a module needs no Go toolchain on the target.

Index

Constants

View Source
const (
	RedfishBackendRedfishtool = "redfishtool"
	RedfishBackendGoRedfish   = "go-redfish"
)

Values of RedfishBackendKey. The empty string, and "redfishtool", are the default: redfishtool on the target through the connection.

View Source
const CheckModeKey = "_ansible_check_mode"

CheckModeKey is how the playbook engine tells a module it is running a dry run. Real Ansible passes the same flag to every module under this exact name, so a module reads it out of its own arguments rather than through a separate parameter — which is also why adding check mode did not change the signature every module in this package is written to.

View Source
const DiffModeKey = "_ansible_diff"

DiffModeKey is the wire flag the engine passes in a task's arguments when the run was started with --diff, matching how real Ansible sends _ansible_diff alongside the module's own parameters. It travels in args for the same reason CheckModeKey does: adding a parameter to every module signature to carry one run-wide boolean would change 566 of them to serve a handful.

View Source
const EnvironmentKey = "_ansible_environment"

EnvironmentKey is the wire flag carrying a task's merged `environment:` into the module, alongside CheckModeKey and DiffModeKey. It travels in args for the same reason those do: one run-wide concern should not add a parameter to 566 signatures.

The engine has already merged the play's entries with the task's own (task wins) and templated every value, so what arrives here is final.

View Source
const MaxDiffSize int64 = 104448

MaxDiffSize is real Ansible's MAX_FILE_SIZE_FOR_DIFF default (ansible/config/base.yml): a file larger than this is reported as skipped rather than diffed, which also bounds the O(n*m) table the renderer builds.

View Source
const RedfishBackendKey = "_goansible_redfish_backend"

Opt-in in-process backend (go-redfish)

By default redfish_command, redfish_config and redfish_info run DMTF's redfishtool ON THE TARGET through the connection (redfishtool_common.go), so the BMC request leaves from the target's network, as it does in real Ansible, where the module runs on the target. That default is unchanged.

The operator may instead ask for the go-redfish client (github.com/go-redfish/redfish), called IN-PROCESS from the go-ansible process: the BMC request then leaves from the CONTROL node, the connection is not used, and no redfishtool is needed on the target. The choice is stated, never inferred from the connection: a become-wrapped or SSH connection to the control node itself would be indistinguishable from a remote one.

The switch travels in args under RedfishBackendKey, the same shape as DiffModeKey and CheckModeKey (a run-wide switch that is not part of any module's argument_spec). The name is deliberately NOT in real Ansible's `_ansible_*` namespace, so that it cannot be mistaken for, or collide with, an internal real Ansible may define later.

How it is set: an engine that includes go-ansible/playbook#215 passes it from the variable goansible_redfish_backend (inventory, play vars, -e), which real Ansible ignores. An engine without #215 does not pass it at all; the only way left is then a task argument, which is NOT portable: real Ansible refuses a parameter outside the module's argument_spec, so a playbook using it fails there.

View Source
const VerboseAlwaysKey = "_ansible_verbose_always"

VerboseAlwaysKey marks a result a stdout callback should print in full without -v. Spelled as real Ansible spells it on the wire.

Variables

View Source
var Docs = docsMerge(docsShards...)

Docs maps every registered module name to its Go doc comment — the same argument/deviation documentation this project has always written on each module<Name> function, extracted once at build time so ansible-doc can print it without the source tree present.

The entries live in the docs_generated_<letter>.go shards beside this file; see gendocs.MaxShardBytes for the measurement that put them there.

Functions

func AcceptsRedfishBackend added in v0.99.0

func AcceptsRedfishBackend(module string) bool

AcceptsRedfishBackend reports whether the module named (bare or FQCN) reads RedfishBackendKey. The engine asks it, rather than keeping its own list, so that a module that learns the key is reached without a change in another repository.

func AsyncCheck added in v0.19.0

func AsyncCheck(ctx context.Context, conn remoteexec.Connection, jid string) (found, done bool, rc int, stdout, stderr string, err error)

func AsyncCleanup added in v0.19.0

func AsyncCleanup(ctx context.Context, conn remoteexec.Connection, jid string) error

AsyncCleanup removes a job's directory entirely — async_status's mode=cleanup.

func AsyncLaunch added in v0.19.0

func AsyncLaunch(ctx context.Context, conn remoteexec.Connection, cmdLine string) (jid string, err error)

AsyncLaunch backgrounds cmdLine on conn's target under a fresh job ID, returning immediately without waiting for it to finish — the command keeps running independently of this call and of the connection itself (nohup traps SIGHUP, so it survives the connection closing), which is the entire point of async:.

A real, disclosed limitation: unlike real Ansible's own async wrapper (which forks/setpgids the job so it can SIGKILL the whole process group if async: 's time limit is exceeded), this does NOT actively kill a job that overruns its time limit — there is no portable POSIX shell equivalent to killpg across every target shell this might run against without a dependency (setsid, part of util-linux) that real targets (macOS/BSD in particular) do not ship by default. AsyncCheck (see below) still enforces the time limit on the CONTROLLER side (a poll loop gives up and reports a timeout failure once the limit passes), it just doesn't reach out and stop the job itself the way real Ansible's wrapper does.

func AsyncResultsFile added in v0.76.0

func AsyncResultsFile(ctx context.Context, conn remoteexec.Connection, jid string) string

AsyncCheck reports a job's current status. found=false means no job directory exists at all for jid (a typo, or AsyncCleanup already ran) — distinct from done=false, which means the directory exists but the job is still running (or, indistinguishably, has not yet written its first byte of output — matching real Ansible's own async_status in that same ambiguous case). done=true gives rc/ stdout/stderr, fetched only then (not on every poll, to avoid hauling potentially large output over the wire while still waiting). AsyncResultsFile resolves the path real reports as `results_file`: the job's own file under the async directory. asyncDirExpr is a SHELL expression ("$HOME/.ansible_async") rather than a path, so $HOME has to be expanded on the TARGET -- reporting the unexpanded form would be a different string than real's.

One extra round trip, taken only where the value is actually reported, which in practice is async_status's own result.

func Collection added in v0.89.0

func Collection(name string) string

Collection reports the collection a module name belongs to. A fully-qualified name resolves like any other, through NormalizeName.

func ComposeCommandLine added in v0.19.0

func ComposeCommandLine(ctx context.Context, conn remoteexec.Connection, module string, args map[string]any) (cmdLine string, skip bool, skipMsg string, err error)

ComposeCommandLine composes the exact shell command line the "command" or "shell" module would execute for args (argv-quoting/ chdir handling included), running the real creates/removes short-circuit check against conn but WITHOUT executing the command itself — skip=true means the command should not run at all (skipMsg explains why, matching what a synchronous run would return via Ok(msg) instead of actually running anything).

Exported for go-ansible/playbook's async: task launcher: command and shell are the only two modules whose entire job reduces to one remote command, and so the only two this port can genuinely background on the target the way async requires — the launcher needs the exact command a synchronous run would use, to wrap it instead of running it directly.

func ContentHeader added in v0.45.0

func ContentHeader(path string) string

ContentHeader is the "<path> (content)" form lineinfile and blockinfile use for both of their headers.

func EnvironmentPrefix added in v0.47.0

func EnvironmentPrefix(args map[string]any) string

EnvironmentPrefix renders a task's environment: as the shell `export` that must precede its command, or "" when there is none.

An export rather than a `FOO=bar cmd` prefix, because a command may itself be `cd somewhere && real-command`: assignments written in front would apply to the `cd` alone, and the command that matters would run without them.

Keys are sorted so the same task produces the same command line twice — a map's order is not one.

func FQCN added in v0.89.0

func FQCN(name string) string

FQCN qualifies a module name the way real ansible-doc prints it: <collection>.<name>. A name already carrying a dot is returned unchanged, and one with no known collection falls back to ansible.builtin -- the old assumption, kept only as a last resort so an unlisted name still prints something shaped like a module name.

func InCheckMode added in v0.41.0

func InCheckMode(args map[string]any) bool

InCheckMode reports whether args carry the dry-run flag.

func InDiffMode added in v0.44.0

func InDiffMode(args map[string]any) bool

InDiffMode reports whether args carry the diff flag.

func NormalizeName added in v0.18.0

func NormalizeName(name string) string

NormalizeName strips a known collection prefix from an FQCN module or playbook-directive reference, returning name unchanged if it carries none of them.

func SupportsCheckMode added in v0.41.0

func SupportsCheckMode(name string) bool

SupportsCheckMode reports whether the named module honours a dry run. A fully-qualified collection name resolves like any other.

Types

type Diff added in v0.44.0

type Diff struct {
	Before, After string

	// BeforeHeader and AfterHeader name each side in the ---/+++ lines.
	// Real modules put the path there, suffixed with "(content)" when
	// the diff is of contents rather than of metadata — an empty header
	// prints the bare word "before"/"after", which is what real Ansible
	// shows for a file that did not exist yet.
	BeforeHeader, AfterHeader string

	// The skip reasons, which real Ansible reports in place of a diff
	// it declines to compute. A non-zero *Larger is the size limit that
	// was exceeded, and is printed as part of the message.
	SrcBinary, DstBinary bool
	SrcLarger, DstLarger int64

	// Prepared is diff text a module formatted itself, emitted verbatim.
	// Real Ansible's `prepared` key; used by modules whose change is not
	// a file's contents.
	Prepared string
}

Diff is a module's before/after report for a --diff run, the Go form of the `diff` key real Ansible modules return. A module fills in only what applies: the common case is Before/After plus the two headers, naming the file each side came from.

Before and After are the file CONTENTS, not paths. An absent side (a file that did not exist) is the empty string, which is what real Ansible's own callback normalizes None to.

func ContentDiff added in v0.44.0

func ContentDiff(beforeHeader, afterHeader string, before, after []byte) Diff

ContentDiff builds a Diff for a file whose contents are changing, applying real Ansible's own binary and size checks to both sides. A nil before means the file did not exist yet.

Both sides are passed in rather than read here, because a module reaches its target through a Connection: the before content comes from the target, which may not be this machine.

The headers are the caller's to choose because real Ansible has NO single convention for them — each module names its sides its own way, measured against ansible-core 2.21.4:

lineinfile, blockinfile  "<path> (content)" on both sides
replace                  the bare path on both sides
copy with content:       the bare dest path on both sides
copy with src:           dest before, the SOURCE path after

A nil before side overrides beforeHeader and leaves it empty, which is what makes real Ansible print a bare "--- before" for a file that did not exist: naming it would claim there were contents to compare.

func (Diff) Empty added in v0.44.0

func (d Diff) Empty() bool

Empty reports whether d carries nothing worth showing.

type Func

type Func func(ctx context.Context, conn remoteexec.Connection, args map[string]any) (Result, error)

Func is a module's entry point. ctx carries cancellation/timeout; conn is already connected to the task's target; args is the task's parameters, already Jinja2-rendered by the caller (this package never templates anything itself). A non-nil error means the module could not determine an outcome at all (a transport failure); an expected failure is a Result with Failed=true and a nil error.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry maps module names to their Func.

func Default

func Default() *Registry

Default returns a Registry pre-populated with this package's built-in module set.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty Registry.

func (*Registry) Get

func (r *Registry) Get(name string) (Func, bool)

Get looks up a module by name. A fully-qualified collection name (FQCN) — "ansible.builtin.copy", "community.general.ufw" — resolves to the same entry as the bare name ("copy", "ufw") once the known collection prefix is stripped; see NormalizeName. This is a deliberate simplification, not full collection-scoped resolution: this registry is a single flat namespace (matching how this port's module set has no real cross-collection name collisions to disambiguate), so an FQCN with the WRONG collection prefix for a given module (e.g. "ansible.builtin.ufw", when ufw is actually community.general's) still resolves — real Ansible would instead fail "couldn't resolve module" in that case. In practice this only diverges from real Ansible on a playbook that already has an incorrect FQCN, which would already be broken there too.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns every registered module name, sorted.

func (*Registry) Register

func (r *Registry) Register(name string, fn Func)

Register adds fn under name, replacing any existing module of the same name (so a caller can override a built-in with a custom module).

func (*Registry) Run

func (r *Registry) Run(ctx context.Context, name string, conn remoteexec.Connection, args map[string]any) (Result, error)

Run looks up name and runs it, returning a Result{Failed:true} (not a Go error) for an unknown module name — matching Ansible's own "couldn't resolve module" being a task failure, not a crash.

type Result

type Result struct {
	Changed bool
	Failed  bool

	// Skipped marks work a module declined to do rather than failed at —
	// today, a command it will not run because this is a dry run. The
	// engine reports it the way it reports any other skipped task.
	Skipped bool

	Msg string

	// NoMsg says this module's result carries NO "msg" key at all,
	// which is not the same as an empty one. Real's `file` returns
	// state/mode/owner and no message, so `r.msg` there is an
	// UNDEFINED variable; real's `command` returns an empty message,
	// so `r.msg` is "". A port that always writes the key is lenient
	// where real raises, and one that omits it whenever it is empty
	// breaks command -- measured, both ways round. So the module that
	// omits it says so.
	NoMsg bool

	Facts map[string]any
	Extra map[string]any

	// Diffs is what changed, for a run started with --diff. A module
	// fills it only when InDiffMode says the caller asked; it is a
	// slice because real Ansible's own callback accepts a list, for a
	// module that touches more than one file.
	Diffs []Diff
}

Result is a module's outcome: Ansible's changed/failed/msg triple, plus optional facts (merged into ansible_facts, e.g. by set_fact) and module-specific extra fields (e.g. command's stdout/stderr/rc).

func AddException added in v0.72.0

func AddException(res Result) Result

addException puts real's `exception` key on a FAILED result.

Real attaches it to every failing module result and to no successful one -- measured across fail, assert, file, command and find: four failures carried it, the one non-failure did not. It is not a per-module concern, which is why it lives here beside finalizeOutput and addPathInfo rather than in 566 modules.

The value is real's own. Where Python has no traceback to show, real emits the literal string below rather than omitting the key, and a Go port never has one -- so this is the honest value, not a stand-in. Measured: `r.exception` after a failing find with limit: 0 is exactly "(traceback unavailable)". It is EXPORTED because two modules do not go through Registry.Run at all: go-ansible/playbook implements `assert` and `debug: var:` in the engine, since both need the host's variables, and a result built there would otherwise be the only failing result without the key.

func Changed

func Changed(msg string) Result

Changed returns a successful, changed result.

func Fail

func Fail(msg string) Result

Fail returns a failed result. Modules normally return this alongside a non-nil error only when the failure is unexpected (a connection error, an unreadable file); an expected, well-formed failure (e.g. the `fail` module itself, or `assert` on a false condition) returns it with a nil error, since it is not the module's own execution that went wrong.

func Ok

func Ok(msg string) Result

Ok returns a successful, unchanged result.

func Skipped added in v0.41.0

func Skipped(msg string) Result

Skipped returns a result for work the module declined to do.

func (Result) WithDiff added in v0.44.0

func (r Result) WithDiff(d Diff) Result

WithDiff returns a copy of r with d appended to Diffs, or r unchanged when d carries nothing worth showing. Modules call it unconditionally and let it decide, which keeps the diff-mode test in one place.

func (Result) WithExtra

func (r Result) WithExtra(key string, value any) Result

WithExtra returns a copy of r with key set in Extra.

Source Files

Directories

Path Synopsis
internal
countsites command
Command countsites counts occurrences of a literal across the .go files of a directory, separating the files that ship from the tests.
Command countsites counts occurrences of a literal across the .go files of a directory, separating the files that ship from the tests.
gendocs
Package gendocs extracts each registered module's Go doc comment (already written on its module<Name> function — this project's convention has always been to document arguments and every deviation from real Ansible's behavior there) and produces the docs_generated*.go sources: a map from each module's registered name to that comment text, for ansible-doc to print without needing the source tree at runtime.
Package gendocs extracts each registered module's Go doc comment (already written on its module<Name> function — this project's convention has always been to document arguments and every deviation from real Ansible's behavior there) and produces the docs_generated*.go sources: a map from each module's registered name to that comment text, for ansible-doc to print without needing the source tree at runtime.
gendocs/cmd/gendocs command
Command gendocs writes the docs_generated*.go sources for the modules package.
Command gendocs writes the docs_generated*.go sources for the modules package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址