You are viewing development documentation built from the latest commit on main (last tag v0.2.0-rc.2, source commit 25e1a892).
APIs and features are subject to change.
Using Kure as a Library
Kure is primarily a Go library. This guide covers the basics of importing it, creating resources, and generating YAML output.
Each Go block below that is not an import block is the body of an Example function in
pkg/kubernetes/library_usage_example_test.go, generated from it, so the page cannot show code
that no longer compiles. go test runs every one of them and compares what it prints, except the
maturity example, which is compiled only: its output follows the pinned upstream modules. Each
import block lists what the examples after it import, less fmt: the examples add fmt.Println
lines to print what they built. They use panic(err) where a program would return the error, and
two things declared in the same file: frontendConfig, a stack.ApplicationConfig that emits one
Deployment, and exportedObjects(), a ConfigMap carrying the resourceVersion, uid and
creationTimestamp an API server sets.
Installation
Creating Resources
A constructor gives you an object with an identity and nothing else: its
apiVersion and kind from the scheme, its metadata.name, and its
metadata.namespace for a namespaced kind. From there the upstream Go struct is
the API, so you set fields on it directly.
kubernetes.Create[appsv1.Deployment]("web", "default") is the generic form;
the per-kind wrappers are generated from the scheme and carry the scope in
their signature, so a cluster-scoped kind takes only a name
(kubernetes.CreateNamespace("platform")).
The base kinds go beyond workloads and RBAC: PriorityClass, EndpointSlice,
Lease, RuntimeClass, the two webhook configurations and the four admission
policy kinds each have a wrapper too (kubernetes.CreatePriorityClass("critical"),
kubernetes.CreateLease("leader", "kube-system")). The Flux image kinds
ImageRepository and ImagePolicy have theirs in pkg/kubernetes/fluxcd, next to
ImageUpdateAutomation. APIService has one as well
(kubernetes.CreateAPIService("v1.example.com")). VerticalPodAutoscaler has none:
it is out of scope. The builder contract
lists
what is covered, why that kind is not, and what a caller does instead.
A kind with a wrapper is also a kind io.ParseYAML returns as its upstream Go
type. That changes what a parse returns when kure starts registering a kind: a
PriorityClass that a strict parse used to refuse, and that a parse with
AllowUnstructured returned as *unstructured.Unstructured, now comes back as
*schedulingv1.PriorityClass. A list document follows its items: a
PriorityClassList, a DeploymentList or a generic List is flattened into its
items, typed where the kind is registered, in the list’s order and in the list’s
place in the stream. A registered type is such a list only where apimachinery
reads its Items as a slice: one whose Items is a nil field of interface
type, or sits behind a nil embedded pointer, is not flattened, and the parse
refuses it with an error instead of panicking. A list whose own metadata carries labels or annotations is
refused, since its items cannot keep them, and so is a document that states
apiVersion, kind or a list’s items under a key in another case (Kind,
Items).
A parse returns the objects that decoded beside the errors of the documents and
list items that did not: check the error and still use the objects. Where the
decoder cannot move past a place in the stream, the parse ends there with one
error, and the objects decoded before it are returned. Malformed JSON after two
JSON objects that open the stream, one after the other with no --- line
between them, is such a place. The IO reference
states the
rules.
One kind is registered at two versions. MetalLB serves BGPPeer at
metallb.io/v1beta1, which it deprecates, and at metallb.io/v1beta2, which it
stores. A manifest at either version parses to that version’s own Go type.
metallb.CreateBGPPeer builds the v1beta2 object, and metallb.AddBGPPeerNodeSelector
takes it with a metav1.LabelSelector. The v1beta1 type has no constructor: build it
from the upstream struct if you need one. Kure does not convert between the two.
Kure adds a helper only for one of a few write shapes: appending one item to a
list, inserting one key into a map, setting a pointer field, or composing a
small upstream struct. A helper never defaults, never validates, and never
touches a field you did not name. A helper writes each argument as you pass
it, or as its JSON encoding where the field holds raw JSON
(fluxcd.SetHelmReleaseValuesFromMap), and computes nothing else from it.
The Kubernetes Builders page is the normative contract: what constructors emit, which helpers exist and why, and the constructor defaults that earlier releases injected and no longer do. If you upgraded and a field you relied on is now empty, that page says which values a constructor sets: identity only, and nothing else.
The per-kind config-struct builders (certmanager.Certificate(&CertificateConfig{...}),
cnpg.Cluster(&ClusterConfig{...}) and the like in certmanager, cnpg,
externalsecrets, prometheus, cilium and volsync) are gone too: build
those kinds with Create<Kind> and the upstream struct, exactly as above. The
Kubernetes Builders
page states the
rule, and the release 2 migration notes
name the upstream field that carries what each config field used to. The values the CNPG builders used to inject are
values you now write yourself.
FluxCD Resources
Helm values given as a map go through fluxcd.SetHelmReleaseValuesFromMap, which marshals them to
JSON and panics on a value encoding/json refuses. Decoded YAML can carry one: gopkg.in/yaml.v3
decodes .nan and .inf into a float NaN or infinity without error, while sigs.k8s.io/yaml
returns that error at decode time. Decode with the latter, or marshal the values yourself and pass
them to fluxcd.SetHelmReleaseValues.
fluxcd.SetFluxInstanceSyncPullSecret and fluxcd.SetFluxInstanceSyncProvider write one field of a
FluxInstance’s spec.sync, creating spec.sync when it is nil. One they create holds only that
field: its kind, url, ref and path, which the CRD requires, are yours to set. An OCIRepository’s
provider and plain-HTTP setting have no helper, since each is a single non-pointer field: assign
them on the OCIRepository, oci.Spec.Provider = "aws" and oci.Spec.Insecure = true.
fluxcd.CreateProvider and fluxcd.CreateAlert emit notification.toolkit.fluxcd.io/v1, which
Flux serves from 2.10 only: a cluster on an older Flux rejects them. Code written against the
v1beta3 types, or against the Flux 2.9 Go APIs, follows
Migrating Provider and Alert to v1
,
which also covers the Secret keys that now fail at runtime and the changed Helm and OCI types.
See the FluxCD Builders reference for all available resource types.
Beyond FluxCD, the Kubernetes Builders
package provides typed constructors for core resources (Deployment, Service, Ingress, CronJob, NetworkPolicy, HTTPRoute), PSA security context helpers, ResourceRequirements builders, and more. The constructors write identity only, so fields the API server requires in context are yours to set: a Job from kubernetes.CreateJob needs Spec.Template.Spec.RestartPolicy set to Never or OnFailure, or the server defaults it to Always and rejects the Job. The Prometheus Builders
sub-package covers ServiceMonitor, PodMonitor, and PrometheusRule CRDs. The MariaDB Builders
sub-package covers the MariaDB operator kinds: MariaDB, its backups, restores and SQL jobs, and the Database, User and Grant objects it manages. Its constructors write identity only, like the others, and it has no constructor for MaxScale, the one kind of the group kure does not register.
kubernetes.ValidateContainerPSA and kubernetes.ValidatePodSpecPSA are opt-in checks of the Pod Security Standards securityContext rules at the baseline and restricted levels. ValidatePodSpecPSA also honors the hostUsers: false and Windows exemptions of the standard. They refuse more specs than earlier releases did, so code that called them can now see a violation. The PSA security contexts
section of the Kubernetes Builders reference lists the rules, the exemptions and the checks that stay out of scope.
Generating YAML
Use the io package to serialize resources. io.Marshal and io.PrintObjectsAsYAML write to
the io.Writer you pass; io.SaveFile writes one object to a path. Every string reads back as
it was, a control character such as NEL or DEL included, which is written as a YAML escape:
Clean YAML encoding
When encoding resources exported from a cluster, server-managed metadata fields (managedFields, resourceVersion, uid, generation, selfLink and the kubectl.kubernetes.io/last-applied-configuration annotation) clutter the output. The default encoding strips all of these automatically, together with a null creationTimestamp and an empty status; a creationTimestamp that is set is kept:
Use ServerFieldStripping to control the level of stripping:
Both encoders write an integer exactly when the object holds it as an integer (an integer field of
a typed object, an int64 in an unstructured one), up to the largest uint64: 9007199254740993
stays 9007199254740993. A float64 that holds an integer between -2^63 and 2^64, both excluded, is
written with the digits of its JSON form, in both field orders, which above 2^53 are not always its
exact expansion: the float64 2^62 is written 4611686018427388000. Hold a large integer as an
integer to have it written exactly.
See the IO reference for all output formats and stripping options.
Asking What Kure Knows About a Kind
Every kind kure registers is described in a table generated from the pinned upstream
module sources (and from the types kure holds itself) — its scope, the module and version it
came from, and the fields
upstream documents as gated, alpha, beta or deprecated. The lookups are in
pkg/kubernetes, and they answer from that table rather than from a hand-kept list.
The row also carries k.ModuleVersion, the pinned version of that module; the example leaves it
out of what it prints because it changes with every dependency bump. One kind of row has no pin:
a kind whose Go type kure holds itself (the VictoriaMetrics kinds of
pkg/kubernetes/victoriametrics) names the module github.com/go-kure/kure with an empty
ModuleVersion, and the operator release its types were copied from is named in the README of
pkg/kubernetes/victoriametrics/api/v1beta1.
The two answer deliberately different questions. KindFor returns the row for one
exact group/version/kind, because GoType, ImportPath and ModuleVersion are
properties of that version. IsNamespaced matches on group and kind only: scope is a
property of the resource, not of the version, so it still answers for a manifest at a
version kure does not register — autoscaling/v1 above, where the scheme carries
autoscaling/v2. KindForAnyVersion is that same version-insensitive match
returning the whole row: the row of the exact version when kure registers it, and
otherwise the first row of the group/kind, whose version-specific fields then describe
another version. pkg/manifest’s Scope builds on the version-insensitive
form, which is why a manifest at an unregistered version is classified rather than
left unknown.
ScopeSource says what declared the scope, and distinguishes a built-in kind from a
custom resource without keeping a list:
The three sources are ScopeSourceMarker (the kind’s own +kubebuilder:resource
marker), ScopeSourceShippedCRD (a CustomResourceDefinition the module ships) and
ScopeSourceBuiltin (the Kubernetes API itself). Only the last is a built-in, and
that distinction decides who wins in manifest.Scope: a built-in’s scope comes from
the table, while for a custom resource a CustomResourceDefinition in the same
context governs — it names the scope the target cluster will serve, where the table
only records what the pinned module declared at build time.
Maturity is reported, never enforced (this example is compiled, not run, because what it prints follows the pinned upstream modules):
kure does not warn, reject or filter on any of it — a consumer with cluster knowledge
decides. The table exists because the failure it describes is silent: the API server
does not reject a field whose feature gate is off, it clears the field and admits the
object, so the manifest reads as applied and is not. The same data is published as
docs/api-tables.json and API Tables
for readers outside
Go. See the Kubernetes Builders
page for what
each column means and how it is derived.
Working with the Domain Model
For more complex scenarios, use the Stack package to define cluster topologies:
Build returns the cluster and an error, which reports an invalid tree.
Then use the Flux Engine and Layout Engine to generate a complete GitOps repository structure. See the Generating Flux Manifests guide for the full workflow.
Error Handling
All Kure packages use the errors package:
Next Steps
- Generating Flux Manifests for the complete workflow
- API Reference for all package documentation
- Examples for working code samples