normalize

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 31 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 normalize normalizes Kubernetes resources so that two YAML representations of the same desired state become byte-identical.

It removes server-managed and defaulted fields according to a Config (see CommonConfig for the embedded defaults), drops resources matching skip rules and writes them in a stable layout:

NAMESPACE/[GROUP_]KIND/NAME.yaml

Cluster-scoped resources use the namespace directory "_cluster".

Index

Constants

View Source
const (
	// ClusterNamespace is the pseudo namespace used for cluster-scoped
	// resources, both for rule matching and as output directory.
	ClusterNamespace = "_cluster"

	// RedactionMarker replaces Secret values when Options.RedactSecrets is set.
	RedactionMarker = "REDACTED"
)
View Source
const StdinPath = "-"

StdinPath is the path argument that means "read from stdin".

Variables

This section is empty.

Functions

func CommonConfig

func CommonConfig() []byte

CommonConfig returns the embedded common config exactly as stored in the binary (including comments).

func Encode

func Encode(w io.Writer, obj map[string]any, headerLines ...string) error

Encode writes obj as YAML exactly like `kubectl get -o yaml` (sigs.k8s.io/yaml: keys sorted, 2-space indent, list items not indented), but with a deterministic key order, see marshalYAML. Each header line is written first as a "# " comment.

func ParseKindsCSV

func ParseKindsCSV(kindFilterCSV string) ([]string, error)

ParseKindsCSV parses a comma-separated list of kind globs. An empty string returns nil (match all).

func ParseNameRegex

func ParseNameRegex(nameRegex string) (*regexp.Regexp, error)

ParseNameRegex compiles the regex. An empty string returns nil (match all).

func ParseNamespacesCSV

func ParseNamespacesCSV(namespacesCSV string) ([]string, error)

ParseNamespacesCSV parses a comma-separated list of namespace names. An empty string returns nil (match all).

func RelPath

func RelPath(item *unstructured.Unstructured, isNamespaced bool) string

RelPath returns the stable relative output path of a resource: NAMESPACE/KIND/NAME.yaml for the core group, NAMESPACE/GROUP_KIND/NAME.yaml otherwise. Cluster-scoped resources use ClusterNamespace.

Types

type Change

type Change struct {
	// Path is the field, e.g. spec.template.spec.containers[0].image.
	Path string
	// Old and New are nil if the field was added or removed.
	Old, New any
	// Reason names the rule or option that made the change.
	Reason string
}

Change is one modification made while normalizing a resource.

type Config

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

Config holds compiled normalization rules: fields to remove, resources to skip and namespaces to exclude. The zero value (or nil) applies no rules.

func LoadConfig

func LoadConfig(useCommon bool, files ...string) (*Config, error)

LoadConfig builds a Config from the embedded common config (if useCommon is true) and the given config files, in this order. Empty file names are ignored.

func (*Config) AddExcludeNamespacesCSV

func (c *Config) AddExcludeNamespacesCSV(csv string) error

AddExcludeNamespacesCSV adds a comma-separated list of namespace globs to exclude. An empty string is a no-op.

func (*Config) AddSkipNameGlob

func (c *Config) AddSkipNameGlob(glob string) error

AddSkipNameGlob adds a skip rule matching resources whose metadata.name matches the anchored glob. An empty glob is a no-op.

func (*Config) ExcludeNamespaces

func (c *Config) ExcludeNamespaces() []string

ExcludeNamespaces returns the namespace globs that are fully excluded.

func (*Config) SkipsEveryResourceOf

func (c *Config) SkipsEveryResourceOf(group, kind string) bool

SkipsEveryResourceOf reports whether a skip rule drops every resource of the given group and kind, regardless of namespace or name. Callers that list resources from an api-server can use this to avoid the LIST call entirely.

type Explanation

type Explanation struct {
	Source string
	// Path is the output path, see RelPath.
	Path string
	// Dropped is the reason why the resource is not part of the output, or
	// "" if it is kept.
	Dropped string
	Changes []Change
}

Explanation tells what normalization does with one resource.

type Options

type Options struct {
	// Config holds the rules (removeFields, skipResources, excludeNamespaces,
	// quantityFields, ...), see LoadConfig. nil applies no rules. Quantity
	// fields declared by CRDs in the input (and WithCRDs) are canonicalized in
	// any case.
	Config *Config

	// Namespaces restricts output to these namespaces (empty = all).
	// Cluster-scoped resources are dropped, except Namespace objects whose
	// name is in the set.
	Namespaces []string

	// Kinds restricts output to kinds matching one of these globs (empty = all).
	Kinds []string

	// NameRegex restricts output to resources whose name matches (nil = all).
	NameRegex *regexp.Regexp

	// SkipOwned drops resources with a controlling owner reference and
	// resources Kubernetes autogenerates (aggregated ClusterRoles, RBAC
	// bootstrap objects, default ServiceAccount, kube-root-ca.crt ConfigMap).
	SkipOwned bool

	// KeepManagedFields keeps metadata.managedFields, even if a rule removes it.
	KeepManagedFields bool

	// RedactSecrets replaces values of core/v1 Secrets with RedactionMarker
	// and drops the last-applied-configuration annotation of Secrets.
	RedactSecrets bool

	// SecretsAsStringData converts base64 Secret data into stringData.
	SecretsAsStringData bool

	// AddNamespaceIfMissing sets metadata.namespace on namespaced resources
	// that have none. Cluster-scoped resources (built-in kinds, CRDs in the
	// input with scope Cluster, clusterScopedResources of the config) are
	// left alone. Applied before filtering.
	AddNamespaceIfMissing string

	// OverwriteNamespace sets metadata.namespace on all namespaced resources,
	// replacing an existing value. Applied before filtering.
	OverwriteNamespace string
	// Warn receives warnings about the input, for example a reference to a
	// namespace that the namespace options cannot move. Nil discards them.
	Warn func(msg string)
	// contains filtered or unexported fields
}

Options controls filtering and normalization.

func (*Options) Explain

func (o *Options) Explain(resources []Resource) ([]Explanation, error)

Explain processes the resources like Process and reports, per resource, every change and the rule that made it.

func (*Options) Include

func (o *Options) Include(item *unstructured.Unstructured, isNamespaced bool) bool

Include reports whether the item passes all filters of o (skip rules, excluded namespaces, kind/name/namespace filters and SkipOwned). isNamespaced tells whether the resource is namespace-scoped. For resources read from files, a resource is namespaced if metadata.namespace is set.

func (*Options) Normalize

func (o *Options) Normalize(obj map[string]any) error

Normalize modifies obj in place: removes managed fields, handles Secrets, applies the removeFields rules and prunes empty labels/annotations.

func (*Options) Process

func (o *Options) Process(resources []Resource) ([]Resource, error)

Process applies namespace handling, filters and normalization. Resources that are filtered out and SOPS-encrypted documents are dropped. The objects are modified in place.

func (*Options) WithCRDs added in v1.2.0

func (o *Options) WithCRDs(resources []Resource) *Options

WithCRDs returns a copy of o that also knows these CustomResourceDefinitions, for example the CRDs of a cluster. Other resources are ignored. Like CRDs in the input of Process, their quantity fields are canonicalized (also by Normalize) and their scope is used by the namespace options.

type Rendered

type Rendered map[string][]byte

Rendered maps the relative output path (see RelPath) to the encoded YAML.

func Render

func Render(resources []Resource, headerLines ...string) (Rendered, error)

Render encodes each resource. Two resources with the same path are an error (the same resource twice, or names like "a:b" and "a_b" that only differ in characters RelPath replaces), because one would silently overwrite the other.

func (Rendered) WriteDir

func (r Rendered) WriteDir(dir string) error

WriteDir writes every file below dir, creating directories as needed. An existing file is an error, never overwritten: on a case-insensitive file system "A.yaml" and "a.yaml" are the same file.

func (Rendered) WriteStream

func (r Rendered) WriteStream(w io.Writer) error

WriteStream writes all documents as one multi-document YAML stream, sorted by path, separated by "---".

type Resource

type Resource struct {
	// Object is the decoded YAML document.
	Object map[string]any
	// Source is the file the document was read from ("-" for stdin).
	Source string
	// SOPSEncrypted is true if the document carries SOPS metadata (a
	// top-level "sops" map with a "mac"). Re-encoding such a document
	// reorders keys and breaks the MAC, so Process skips it.
	SOPSEncrypted bool
}

Resource is a single Kubernetes object read from a YAML document.

func CloneResources

func CloneResources(resources []Resource) []Resource

CloneResources returns a deep copy, so the resources can be processed twice (Process modifies objects in place) without parsing again.

func ParseYAML

func ParseYAML(data []byte, source string) ([]Resource, error)

ParseYAML parses a (multi-document) YAML stream the way kubectl does (sigs.k8s.io/yaml, YAML 1.1 semantics, duplicate keys are an error). Documents without metadata (for example kustomization.yaml) and empty documents are skipped.

func ReadPaths

func ReadPaths(inputPaths []string, stdin io.Reader) ([]Resource, error)

ReadPaths reads all resources from files, directories (recursively, *.yaml and *.yml) or stdin ("-", which must be the only input). A file given twice (directly and via its directory) is read once.

func (*Resource) Namespaced

func (r *Resource) Namespaced() bool

Namespaced reports whether metadata.namespace is set. Without an api-server this is the only reliable signal: resources without namespace are treated as cluster-scoped for the output layout.

func (*Resource) RelPath

func (r *Resource) RelPath() string

RelPath returns the stable relative output path, see RelPath.

func (*Resource) Unstructured

func (r *Resource) Unstructured() *unstructured.Unstructured

Unstructured wraps the object without copying it.

Jump to

Keyboard shortcuts

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