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
Resources without metadata.namespace use the directory "_cluster".
Data flow ¶
- Read: ReadPaths reads files, directories and stdin, ParseYAML splits a stream into one Resource per document (List kinds are expanded, SOPS-encrypted documents are marked).
- Configure: LoadConfig compiles the common config and user files into a Config. Options holds the Config plus the CLI choices (namespace handling, filters, secrets, labels and annotations to set). WithCRDs adds CRDs that are not part of the input.
- Process: Options.Process sets namespaces, drops filtered and SOPS-encrypted resources and normalizes the rest in place: remove rules, then setMetadata rules, then the labels and annotations of the Options. Explain does the same and records every change.
- Write: Render encodes the resources like kubectl and maps them to their paths (two resources on one path are an error). Rendered.WriteDir writes one file per resource and never overwrites a file; Rendered.WriteStream writes one multi-document stream.
Files ¶
- resource.go: Resource, reading, Process, Render, writing.
- config.go: the config format, LoadConfig, rule compilation.
- common-config.yaml: the embedded common config.
- normalize.go: Options and the per-resource normalization.
- fields.go: field paths with globs, removing fields.
- filter.go: skip rules, --kind, --name-regex, --namespaces, SkipOwned.
- namespace.go: scope of kinds (built-in, CRDs, config) and namespace handling, including references to namespaces in other objects.
- quantity.go: canonical quantities (1000m becomes "1").
- secrets.go: redacting Secrets or converting data to stringData.
- marshal.go: YAML output with the key order of kubectl.
- explain.go: the trace behind Explain.
- parallel.go: the worker pool used by ReadPaths and Process.
Example ¶
Normalize helm output with the common config and print it as one stream.
package main
import (
"fmt"
"os"
"github.com/guettli/kubenorm/normalize"
)
func main() {
input := []byte(`apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
helm.sh/chart: web-1.2.3
spec:
replicas: 1
template:
spec:
containers:
- name: web
image: nginx:1.27
resources:
limits:
cpu: 1000m
`)
cfg, err := normalize.LoadConfig(true)
if err != nil {
fmt.Println(err)
return
}
resources, err := normalize.ParseYAML(input, "helm-output.yaml")
if err != nil {
fmt.Println(err)
return
}
opts := &normalize.Options{Config: cfg, AddNamespaceIfMissing: "demo"}
resources, err = opts.Process(resources)
if err != nil {
fmt.Println(err)
return
}
rendered, err := normalize.Render(resources)
if err != nil {
fmt.Println(err)
return
}
err = rendered.WriteStream(os.Stdout)
if err != nil {
fmt.Println(err)
}
}
Output: --- apiVersion: apps/v1 kind: Deployment metadata: name: web namespace: demo spec: replicas: 1 template: spec: containers: - image: nginx:1.27 name: web resources: limits: cpu: "1"
Index ¶
- Constants
- func CommonConfig() []byte
- func Encode(w io.Writer, obj map[string]any, headerLines ...string) error
- func ParseKindsCSV(kindFilterCSV string) ([]string, error)
- func ParseNameRegex(nameRegex string) (*regexp.Regexp, error)
- func ParseNamespacesCSV(namespacesCSV string) ([]string, error)
- func RelPath(item *unstructured.Unstructured, isNamespaced bool) string
- type Change
- type Config
- type Explanation
- type Options
- func (o *Options) Explain(resources []Resource) ([]Explanation, error)
- func (o *Options) Include(item *unstructured.Unstructured, isNamespaced bool) bool
- func (o *Options) Normalize(obj map[string]any) error
- func (o *Options) Process(resources []Resource) ([]Resource, error)
- func (o *Options) WithCRDs(resources []Resource) *Options
- type Rendered
- type Resource
Examples ¶
Constants ¶
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" // RenderedByAnnotation names the script or pipeline that rendered a // resource, see Options.RenderedBy and the --rendered-by flag of the // kubenorm CLI. Unlike // app.kubernetes.io/managed-by (the tool that manages the resource in // the cluster) it allows any value, for example a path. RenderedByAnnotation = "kubenorm.guettli.github.io/rendered-by" )
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 ¶
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 ¶
ParseKindsCSV parses a comma-separated list of kind globs. An empty string returns nil (match all).
func ParseNameRegex ¶
ParseNameRegex compiles the regex. An empty string returns nil (match all).
func ParseNamespacesCSV ¶
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, read from the top-level config keys removeFields (fields to remove), skipResources (resources to drop), excludeNamespaces (namespaces to drop with everything inside), quantityFields (fields to canonicalize as quantities), clusterScopedResources (kinds to treat as cluster-scoped), setMetadata (labels and annotations to set), ownerHints (who manages a resource, for kubenorm diff) and keepFields (fields no removeFields rule removes). The zero value (or nil) applies no rules.
func LoadConfig ¶
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 ParseConfig ¶ added in v1.17.0
ParseConfig parses a single YAML config document, like a file given to LoadConfig, but without the common config. Unknown keys are rejected. name is only used in error messages and in the origin of rules (see explain).
func (*Config) AddExcludeNamespacesCSV ¶
AddExcludeNamespacesCSV adds a comma-separated list of namespace globs to exclude. An empty string is a no-op.
func (*Config) AddSkipNameGlob ¶
AddSkipNameGlob adds a skip rule matching resources whose metadata.name matches the anchored glob. An empty glob is a no-op.
func (*Config) ExcludeNamespaces ¶
ExcludeNamespaces returns the namespace globs that are fully excluded. dumpall uses it to skip LIST calls in excluded namespaces.
func (*Config) OwnerHints ¶ added in v1.32.0
OwnerHints returns the hints of the ownerHints rules of the config that apply to a resource with these labels and annotations, in the order of the config files.
func (*Config) SkipsEveryResourceOf ¶
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; dumpall does so.
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
// and their schema defaults removed 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
// SetLabels sets these labels in metadata.labels of every resource,
// replacing existing values. Applied after the remove rules, so a rule
// does not remove them. Pod templates and selectors are not changed.
SetLabels map[string]string
// SetAnnotations sets these annotations in metadata.annotations of every
// resource, like SetLabels.
SetAnnotations map[string]string
// RenderedBy sets the annotation RenderedByAnnotation of every resource,
// like SetAnnotations. It must not contain control characters.
RenderedBy 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 ¶
Normalize modifies obj in place: removes managed fields, handles Secrets, canonicalizes quantityFields, applies the removeFields and setMetadata rules, sets SetLabels, SetAnnotations and RenderedBy and prunes empty labels/annotations.
Unlike Process, it handles a single object and skips everything that needs the other resources or decides about keeping one: no namespace options (AddNamespaceIfMissing, OverwriteNamespace), no filters (skip rules, excludeNamespaces, Namespaces, Kinds, NameRegex, SkipOwned; see Include) and no rules from CRDs in the input (quantities, defaults; use WithCRDs). Use Process for files and streams of resources; use Include and Normalize for objects streamed one by one, for example from an api-server.
func (*Options) Process ¶
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
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 and fields that hold their schema defaults are removed (also by Normalize), and their scope is used by the namespace options.
type Rendered ¶
Rendered maps the relative output path (see RelPath) to the encoded YAML.
func Render ¶
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.
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 ¶
CloneResources returns a deep copy, so the resources can be processed twice (Process modifies objects in place) without parsing again.
func ParseYAML ¶
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 ¶
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 ¶
Namespaced reports whether the resource has metadata.namespace. Without an api-server this is the only reliable signal: every resource without namespace, also one of a namespaced kind, is treated like a cluster-scoped one: it goes to ClusterNamespace and matches it in rules and filters.
func (*Resource) Unstructured ¶
func (r *Resource) Unstructured() *unstructured.Unstructured
Unstructured wraps the object without copying it.