envref

package
v1.4.6 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 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.

Documentation

Overview

Package envref expands ${VAR} references in configuration values, so secrets can live outside config files (for example injected by Kubernetes envFrom from a Secret synced out of AWS Secrets Manager) while the config file keeps describing the structure. DecodeYAML is the entry point for YAML files.

Syntax, a strict subset of docker compose interpolation:

${NAME}          required; unset or empty is an error
${NAME:-value}   optional; unset or empty falls back to value (may be
                 empty, may not contain '}' or another reference)
$${              literal "${"

Any other "$" is left untouched, so existing values such as "a$b" or "$$" keep their meaning. NAME must match [A-Za-z_][A-Za-z0-9_]*.

Differences from compose are deliberate: a missing required variable fails instead of silently becoming "", and substituted values are never expanded again, so a secret that happens to contain "${...}" is used verbatim.

Expansion runs on parsed values, never on raw file text, so values containing quotes, '#', ':' or newlines cannot alter the document structure.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DecodeError

type DecodeError struct {
	// Paths lists config paths whose values were expanded, sorted and capped
	// at 20.
	Paths []string
}

DecodeError replaces a decode error whose message could not be checked for expanded values. The original error is deliberately not wrapped.

func (*DecodeError) Error

func (e *DecodeError) Error() string

type MissingError

type MissingError struct {
	// Names is sorted and de-duplicated.
	Names []string
	// Paths maps each name to the config paths that reference it, sorted and
	// capped at 10 per name.
	Paths map[string][]string
}

MissingError lists required variables that were unset or empty.

func (*MissingError) Error

func (e *MissingError) Error() string

type Option

type Option func(*options)

Option configures expansion.

func WithSource

func WithSource(s Source) Option

WithSource replaces the default Env() source. A nil source provides no variables at all (every reference is missing); it never falls back to the process environment, so a caller that meant a restricted source cannot leak the environment by accident.

type Result

type Result struct {
	// Referenced lists every variable name that appeared in a reference,
	// sorted and de-duplicated. Callers use it to keep those variables out of
	// places that must not see secrets, such as a script sandbox or a debug
	// dump of the environment.
	Referenced []string
}

Result reports what an expansion touched.

func DecodeYAML

func DecodeYAML(data []byte, out any, opts ...Option) (*Result, error)

DecodeYAML decodes the first YAML document in data into out, expanding references in scalar values on the way, the same order docker compose uses: parse into a node tree, interpolate values on the tree, then decode into the typed struct.

Only values are expanded; mapping keys are left alone. Because expansion works on parsed nodes, a value containing quotes, '#', ':' or newlines can never change the document structure.

Typing follows how the value was written:

port: ${DB_PORT}      plain: re-typed after expansion, so 5432 decodes into an int field
password: "${DB_PW}"  quoted: always a string

Quote references to secrets. A plain reference is re-typed by YAML rules, so when the target is an interface (any, map[string]any) a secret such as "0123" or "1e3" would be decoded as a number.

Inside flow collections ({...} or [...]) the reference must be quoted: "{" and "}" are flow indicators, so {port: ${P}} is not valid YAML.

A plain value that expands to something YAML reads as null ("null", "~") is kept as a string: whoever wrote ${X} meant a value, and silently zeroing a password because the secret happens to be "null" is worse than surprising. A plain value that expands to nothing (only possible through an empty default such as ${X:-}) stays null, so the field keeps its default; write "${X:-}" with quotes to get an empty string instead.

A key written with no value follows yaml.v3: string, number, bool and struct fields keep what out already held (usually a default), while pointer, map, slice and interface fields are reset. yaml.v2 reset all of them, so configs that relied on "key:" meaning "empty" should write key: "" instead.

Every missing variable is reported in one *MissingError, and out is not touched unless all references resolve. If decoding itself fails, out may be partly filled, as with yaml.Unmarshal. Decoding is not strict: unknown fields are ignored.

Decoding uses go.yaml.in/yaml/v3. Custom unmarshalers written against gopkg.in/yaml.v3 (UnmarshalYAML(*yaml.Node) with that module's Node type) are a different type and are not called; implement them with go.yaml.in/yaml/v3, or use the UnmarshalYAML(func(any) error) form.

Decode errors never carry expanded values. In a *yaml.TypeError, each entry on a line that holds an expanded value is replaced by one naming the config path instead of the value; other entries are kept. Any other decode error (for example from a TextUnmarshaler, which may quote its input in any form) is replaced by a *DecodeError when the document contains expanded values. A custom unmarshaler that builds its own *yaml.TypeError must report the line of the node whose value it echoes; an entry attributed to a parent node's line is kept as written.

DecodeYAML is meant for trusted configuration files. Error messages list config paths, which for deeply nested documents with many missing references can be long; paths per variable and per line are capped.

func ExpandString

func ExpandString(s string, opts ...Option) (string, *Result, error)

ExpandString expands the references in s.

On a missing required variable it returns a *MissingError; on a malformed reference it returns a *SyntaxError. Neither error ever contains a resolved value.

func (*Result) Contains

func (r *Result) Contains(name string) bool

Contains reports whether name was referenced.

type Source

type Source interface {
	Lookup(name string) (string, bool)
}

Source supplies the value of a referenced variable.

A value that is not found, or found but empty, is treated as missing by the expander; sources do not need to special-case empty values.

func Chain

func Chain(sources ...Source) Source

Chain returns a Source that asks each source in order and returns the first non-empty value. It lets a later migration add, say, a mounted-secret directory behind the environment without touching config files.

func Env

func Env() Source

Env returns a Source backed by the process environment.

func Map

func Map(values map[string]string) Source

Map returns a Source backed by a fixed map, mainly for tests.

type SourceFunc

type SourceFunc func(name string) (string, bool)

SourceFunc adapts a plain function to Source.

func (SourceFunc) Lookup

func (f SourceFunc) Lookup(name string) (string, bool)

Lookup calls f(name).

type SyntaxError

type SyntaxError struct {
	Path   string
	Reason string
}

SyntaxError reports a malformed reference. It carries the config path, not the offending value.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Jump to

Keyboard shortcuts

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