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
- func CommonConfig() []byte
- func Encode(w io.Writer, obj map[string]any, headerLines ...string) error
- func FormatValue(v any, maxLen int) string
- func ParseKindsCSV(kindFilterCSV string) ([]string, error)
- func ParseNameRegex(nameRegex string) (*regexp.Regexp, error)
- func ParseNamespacesCSV(namespacesCSV string) (map[string]struct{}, error)
- func RelPath(item *unstructured.Unstructured, isNamespaced bool) string
- type Change
- type Config
- type Explanation
- type FileDiff
- type FileStatus
- type Labels
- 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) SkipReason(item *unstructured.Unstructured, isNamespaced bool) string
- func (o *Options) Validate() error
- type Rendered
- type Resource
- type SourceDiff
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" )
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 FormatValue ¶
FormatValue renders a value compactly on one line, shortened to maxLen.
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 an empty (match-all) filter.
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 ¶
LoadConfig builds a Config from the embedded common config (if useCommon is true) and the optional user config file. Both are merged.
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.
func (*Config) HasRemoveRules ¶
HasRemoveRules reports whether the config contains at least one removeFields rule.
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.
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 FileDiff ¶
type FileDiff struct {
// Path is the relative path, see RelPath.
Path string
Status FileStatus
// Unified is the unified diff (git apply compatible).
Unified string
}
FileDiff is the difference of one resource.
func ComputeDiff ¶
ComputeDiff compares old and new, sorted by path.
type FileStatus ¶
type FileStatus byte
FileStatus tells how a resource differs.
const ( // StatusAdded means the resource only exists on the new side. StatusAdded FileStatus = 'A' // StatusModified means the resource differs. StatusModified FileStatus = 'M' // StatusDeleted means the resource only exists on the old side. StatusDeleted FileStatus = 'D' )
type Labels ¶
Labels returns the "---" and "+++" labels of the diff of a resource.
func PrefixLabels ¶
PrefixLabels labels a resource with its path below the given prefixes, like git diff does.
type Options ¶
type Options struct {
// Config holds removeFields, skipResources and excludeNamespaces rules.
// nil applies no rules.
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 map[string]struct{}
// 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 are left alone (see
// isBuiltinClusterScoped). 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)
}
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, applies the removeFields rules and prunes empty labels/annotations.
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) SkipReason ¶
func (o *Options) SkipReason(item *unstructured.Unstructured, isNamespaced bool) string
SkipReason returns why the item is dropped, or "" if it is kept.
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 identity are an error, because one would silently overwrite the other.
func (Rendered) SortedPaths ¶
SortedPaths returns the keys sorted.
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 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) Unstructured ¶
func (r *Resource) Unstructured() *unstructured.Unstructured
Unstructured wraps the object without copying it.
type SourceDiff ¶
SourceDiff holds the differences of one input file.
func DiffBySource ¶
func DiffBySource(oldSide, newSide []Resource, labels func(source string) Labels) ([]SourceDiff, error)
DiffBySource compares two processed versions of the same input file by file (for example raw and normalized). Comparing per file allows separate trees with the same resources. labels returns the diff labels for a source file. Files are compared in parallel, the result keeps the order in which the files first appear in oldSide.