Documentation
¶
Overview ¶
Package kubernetes provides the scheme, the generic constructor and the admissible sugar helpers for building Kubernetes objects under the builder contract (ADR-038). The contract text is the package README; this comment is the map.
Construction ¶
The upstream Go struct is the construction API: obtain an object, then write its fields directly (obj.Spec.Replicas = ptr.To[int32](3)). kure does not wrap plain field access.
Create allocates any type registered in the scheme and sets exactly its TypeMeta (from the scheme), metadata.name and metadata.namespace. Nothing else: no labels, no annotations, no selector, no defaults. An unregistered type panics. Cluster-scoped kinds take "" as namespace.
d := kubernetes.Create[appsv1.Deployment]("web", "default")
The per-kind wrappers (CreateDeployment, CreateNamespace, ...) in zz_generated_create.go are generated from the scheme by pkg/kubernetes/internal/gen; cluster-scoped kinds take only a name. They are one-line calls to Create and are never hand-written.
Metadata ¶
SetLabels, AddLabel, SetAnnotations and AddAnnotation work on any metav1.Object and are the only metadata helpers the contract keeps.
Sugar ¶
An exported Set*/Add* function is admitted by class: slice append or map insert, pointer-typed field assignment (which covers nil-init of an intermediate), or an upstream struct literal of two or more fields or with a nested literal. Every admitted operation carries a value the caller supplied and happens in the helper's own body, which has no function literal, and every write goes through the one pointer parameter the helper takes its object by, not a local or alias. The body is written in a closed grammar, which the README states rule by rule: nil guards that panic and the marshalled form of an argument, then nil-init guards and single assignments, each writing an argument passed whole and used once, and every parameter is the object, a key or such an argument. A body that assigns nil to a field, writes a value the caller did not pass, or takes its object by value, and a helper that returns anything or declares type parameters, are inadmissible whatever else they do. A test classifies every helper with go/ast and fails on anything outside those classes that is not listed in testdata/admission_exclusions.txt; that list held the legacy helpers (bare forwarders, error-returning and validating setters) while the prune work item of the builder-contract epic ran, and is now empty. It only ever shrinks. Every helper here panics on a nil receiver, takes exactly the value it writes, and never defaults or validates.
GVK Utilities ¶
GetGroupVersionKind resolves the GroupVersionKind of any runtime.Object registered with the package scheme. IsGVKAllowed checks a GVK against a user-defined allow list.
Scheme Registration ¶
RegisterSchemes initialises the shared runtime.Scheme covering the Kubernetes built-in types and every CRD family kure builds for. The scheme is registered lazily on first use and is safe for concurrent access.
PSA Security Context Helpers ¶
RestrictedPodSecurityContext, BaselinePodSecurityContext and PrivilegedPodSecurityContext return PodSecurityContext values for the corresponding Pod Security Standards levels; RestrictedSecurityContext, BaselineSecurityContext and PrivilegedSecurityContext do the same for containers. PodSecurityContextForLevel and SecurityContextForLevel select by PSALevel. ValidateContainerPSA and ValidatePodSpecPSA are explicit, opt-in checks; nothing in this package calls them for you.
Example (ArchitectureRBAC) ¶
package main
import (
"fmt"
rbacv1 "k8s.io/api/rbac/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
// Create minimal privilege roles
role := kubernetes.CreateRole("app-reader", "default")
kubernetes.AddRoleRule(role, rbacv1.PolicyRule{
APIGroups: []string{""},
Resources: []string{"pods"},
Verbs: []string{"get", "list"},
})
// Bind to specific accounts. RoleRef is a single struct field, so it is written
// directly - a helper for it would be the assignment with more words.
binding := kubernetes.CreateRoleBinding("app-reader", "default")
binding.RoleRef = rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Kind: "Role",
Name: "app-reader",
}
kubernetes.AddRoleBindingSubject(binding, rbacv1.Subject{
Kind: "ServiceAccount",
Name: "app-sa",
})
fmt.Println(role.Rules[0].Verbs, binding.RoleRef.Kind, binding.Subjects[0].Name)
}
Output: [get list] Role app-sa
Example (BuilderContractGeneric) ¶
package main
import (
"fmt"
appsv1 "k8s.io/api/apps/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
d := kubernetes.Create[appsv1.Deployment]("web", "default")
fmt.Println(d.APIVersion, d.Kind, d.Namespace, d.Name)
}
Output: apps/v1 Deployment default web
Example (BuilderContractNamespace) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
ns := kubernetes.CreateNamespace("platform")
fmt.Println(ns.Kind, ns.Name, ns.Namespace == "")
}
Output: Namespace platform true
Example (BuilderContractStrategy) ¶
package main
import (
"fmt"
appsv1 "k8s.io/api/apps/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
d := kubernetes.CreateDeployment("web", "default")
// There is no SetDeploymentStrategy. This is what it would have done.
d.Spec.Strategy = appsv1.DeploymentStrategy{Type: appsv1.RecreateDeploymentStrategyType}
fmt.Println(d.Spec.Strategy.Type)
}
Output: Recreate
Example (LibraryUsageCreate) ¶
package main
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
dep := kubernetes.CreateDeployment("web", "default") // identity only
dep.Spec.Replicas = ptr.To[int32](3)
dep.Spec.Selector = &metav1.LabelSelector{MatchLabels: map[string]string{"app": "web"}}
dep.Spec.Template.Spec.ServiceAccountName = "web"
fmt.Println(dep.Kind, dep.Name, *dep.Spec.Replicas, dep.Spec.Selector.MatchLabels["app"])
}
Output: Deployment web 3 web
Example (LibraryUsageDomainModel) ¶
package main
import (
"fmt"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/go-kure/kure/pkg/kubernetes"
"github.com/go-kure/kure/pkg/stack"
)
// frontendConfig is the stack.ApplicationConfig the guide's domain-model
// example uses: one Deployment named after the application.
var frontendConfig stack.ApplicationConfig = deploymentApp{}
type deploymentApp struct{}
func (deploymentApp) Generate(app *stack.Application) ([]*client.Object, error) {
var obj client.Object = kubernetes.CreateDeployment(app.Name, app.Namespace)
return []*client.Object{&obj}, nil
}
func main() {
cluster, err := stack.NewClusterBuilder("production").
WithNode("apps").
WithBundle("web").
WithApplication("frontend", frontendConfig).
End().
End().
Build()
if err != nil {
panic(err)
}
fmt.Println(cluster.Name, cluster.Node.Name, cluster.Node.Bundle.Name)
}
Output: production apps web
Example (LibraryUsageEncodeDefault) ¶
package main
import (
"fmt"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/go-kure/kure/pkg/io"
"github.com/go-kure/kure/pkg/kubernetes"
)
// exportedObjects is what the guide's encoding examples serialize: a
// ConfigMap carrying the metadata an API server sets, as when it is read back
// from a cluster.
func exportedObjects() []*client.Object {
cm := kubernetes.CreateConfigMap("app-config", "default")
cm.Data = map[string]string{"LOG_LEVEL": "info"}
cm.ResourceVersion = "48213"
cm.UID = "0f6c1d9e-2b7a-4c55-9d3e-6a1b2c3d4e5f"
cm.CreationTimestamp = metav1.NewTime(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC))
var obj client.Object = cm
return []*client.Object{&obj}
}
func main() {
objects := exportedObjects()
// Default: strips server-managed fields and uses standard key order
data, err := io.EncodeObjectsToYAMLWithOptions(objects, io.EncodeOptions{
KubernetesFieldOrder: true,
})
if err != nil {
panic(err)
}
fmt.Print(string(data))
}
Output: apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: "2026-01-02T03:04:05Z" name: app-config namespace: default data: LOG_LEVEL: info
Example (LibraryUsageEncodeNone) ¶
package main
import (
"fmt"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/go-kure/kure/pkg/io"
"github.com/go-kure/kure/pkg/kubernetes"
)
// exportedObjects is what the guide's encoding examples serialize: a
// ConfigMap carrying the metadata an API server sets, as when it is read back
// from a cluster.
func exportedObjects() []*client.Object {
cm := kubernetes.CreateConfigMap("app-config", "default")
cm.Data = map[string]string{"LOG_LEVEL": "info"}
cm.ResourceVersion = "48213"
cm.UID = "0f6c1d9e-2b7a-4c55-9d3e-6a1b2c3d4e5f"
cm.CreationTimestamp = metav1.NewTime(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC))
var obj client.Object = cm
return []*client.Object{&obj}
}
func main() {
objects := exportedObjects()
// Preserve server fields (e.g. for debugging)
data, err := io.EncodeObjectsToYAMLWithOptions(objects, io.EncodeOptions{
ServerFieldStripping: io.StripServerFieldsNone,
})
if err != nil {
panic(err)
}
fmt.Print(string(data))
}
Output: apiVersion: v1 data: LOG_LEVEL: info kind: ConfigMap metadata: creationTimestamp: "2026-01-02T03:04:05Z" name: app-config namespace: default resourceVersion: "48213" uid: 0f6c1d9e-2b7a-4c55-9d3e-6a1b2c3d4e5f
Example (LibraryUsageErrors) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/errors"
"github.com/go-kure/kure/pkg/io"
)
func main() {
load := func(path string) error {
_, err := io.ParseFile(path)
if err != nil {
return errors.Wrap(err, "failed to generate manifests")
}
return nil
}
fmt.Println(load("does-not-exist.yaml"))
}
Output: failed to generate manifests: open does-not-exist.yaml: no such file or directory
Example (LibraryUsageFlux) ¶
package main
import (
"fmt"
"time"
kustv1 "github.com/fluxcd/kustomize-controller/api/v1"
sourcev1 "github.com/fluxcd/source-controller/api/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/go-kure/kure/pkg/kubernetes/fluxcd"
)
func main() {
// Create a GitRepository source
repo := fluxcd.CreateGitRepository("my-repo", "flux-system")
repo.Spec.URL = "https://github.com/org/repo"
fluxcd.SetGitRepositoryReference(repo, &sourcev1.GitRepositoryRef{Branch: "main"})
repo.Spec.Interval = metav1.Duration{Duration: 5 * time.Minute}
// Create a Kustomization that references the source
ks := fluxcd.CreateKustomization("my-app", "flux-system")
ks.Spec.SourceRef = kustv1.CrossNamespaceSourceReference{
Kind: "GitRepository",
Name: "my-repo",
}
ks.Spec.Path = "./clusters/production"
ks.Spec.Interval = metav1.Duration{Duration: 10 * time.Minute}
ks.Spec.Prune = true
fmt.Println(repo.Spec.Reference.Branch, ks.Spec.SourceRef.Kind+"/"+ks.Spec.SourceRef.Name, ks.Spec.Path)
}
Output: main GitRepository/my-repo ./clusters/production
Example (LibraryUsageHelpers) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
dep := kubernetes.CreateDeployment("web", "default")
kubernetes.AddLabel(dep, "tier", "frontend") // works on any kind
kubernetes.SetDeploymentReplicas(dep, 3)
fmt.Println(dep.Labels["tier"], *dep.Spec.Replicas)
}
Output: frontend 3
Example (LibraryUsageKindFor) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
k, ok := kubernetes.KindFor("apps/v1", "Deployment") // exact group/version/kind
if ok {
fmt.Println(k.Namespaced, k.Module, k.ScopeSource)
}
namespaced, known := kubernetes.IsNamespaced("autoscaling/v1", "HorizontalPodAutoscaler")
fmt.Println(namespaced, known)
}
Output: true k8s.io/api builtin true true
Example (LibraryUsageMaturity) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
for _, f := range kubernetes.MaturityForType("k8s.io/api/core/v1", "PodSpec") {
fmt.Println(f.Field, f.Stability, f.Gates)
}
gated := kubernetes.GatedFields() // every field behind a feature gate
fmt.Println(len(gated) > 0)
}
Output:
Example (LibraryUsageScopeSource) ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
"github.com/go-kure/kure/pkg/manifest"
)
func main() {
k, _ := kubernetes.KindForAnyVersion("cilium.io/v2", "CiliumNetworkPolicy")
fmt.Println(k.ScopeSource == kubernetes.ScopeSourceBuiltin) // false: declared by a marker
// pkg/manifest asks both forms of the scope question:
fmt.Println(manifest.IsNamespacedKind("cilium.io/v2", "CiliumNetworkPolicy")) // true
fmt.Println(manifest.IsNamespacedBuiltinKind("cilium.io/v2", "CiliumNetworkPolicy")) // false, not a built-in
}
Output: false true false
Example (LibraryUsageYAML) ¶
package main
import (
"os"
"path/filepath"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/go-kure/kure/pkg/io"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
cm := kubernetes.CreateConfigMap("app-config", "default")
cm.Data = map[string]string{"LOG_LEVEL": "info"}
var obj client.Object = cm
objects := []*client.Object{&obj}
dir, err := os.MkdirTemp("", "kure-library-usage")
if err != nil {
panic(err)
}
defer func() { _ = os.RemoveAll(dir) }()
// Serialize a single object
if err := io.Marshal(os.Stdout, cm); err != nil {
panic(err)
}
// Write multiple objects to stdout as YAML
if err := io.PrintObjectsAsYAML(objects, os.Stdout); err != nil {
panic(err)
}
// Save to file
if err := io.SaveFile(filepath.Join(dir, "output.yaml"), cm); err != nil {
panic(err)
}
}
Output: apiVersion: v1 data: LOG_LEVEL: info kind: ConfigMap metadata: name: app-config namespace: default apiVersion: v1 data: LOG_LEVEL: info kind: ConfigMap metadata: name: app-config namespace: default
Example (SiteIndex) ¶
package main
import (
"os"
"github.com/go-kure/kure/pkg/io"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
cm := kubernetes.CreateConfigMap("app-config", "default")
kubernetes.AddConfigMapData(cm, "DATABASE_HOST", "postgres.db.svc")
kubernetes.AddConfigMapData(cm, "DATABASE_PORT", "5432")
if err := io.Marshal(os.Stdout, cm); err != nil {
panic(err)
}
}
Output: apiVersion: v1 data: DATABASE_HOST: postgres.db.svc DATABASE_PORT: "5432" kind: ConfigMap metadata: name: app-config namespace: default
Index ¶
- Variables
- func AddAnnotation(obj metav1.Object, key, value string)
- func AddClusterRoleBindingSubject(crb *rbacv1.ClusterRoleBinding, subject rbacv1.Subject)
- func AddClusterRoleRule(cr *rbacv1.ClusterRole, rule rbacv1.PolicyRule)
- func AddConfigMapBinaryData(cm *corev1.ConfigMap, key string, value []byte)
- func AddConfigMapData(cm *corev1.ConfigMap, key, value string)
- func AddContainerEnv(container *corev1.Container, env corev1.EnvVar)
- func AddContainerEnvFrom(container *corev1.Container, envFrom corev1.EnvFromSource)
- func AddContainerPort(container *corev1.Container, port corev1.ContainerPort)
- func AddContainerVolumeDevice(container *corev1.Container, volumeDevice corev1.VolumeDevice)
- func AddContainerVolumeMount(container *corev1.Container, volumeMount corev1.VolumeMount)
- func AddHPACPUMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, targetUtilization int32)
- func AddHPACustomMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, metric autoscalingv2.MetricSpec)
- func AddHPAMemoryMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, targetUtilization int32)
- func AddHTTPRouteHostname(route *gwapiv1.HTTPRoute, hostname gwapiv1.Hostname)
- func AddHTTPRouteParentRef(route *gwapiv1.HTTPRoute, ref gwapiv1.ParentReference)
- func AddHTTPRouteRule(route *gwapiv1.HTTPRoute, rule gwapiv1.HTTPRouteRule)
- func AddHTTPRouteRuleBackendRef(rule *gwapiv1.HTTPRouteRule, ref gwapiv1.HTTPBackendRef)
- func AddHTTPRouteRuleFilter(rule *gwapiv1.HTTPRouteRule, filter gwapiv1.HTTPRouteFilter)
- func AddHTTPRouteRuleMatch(rule *gwapiv1.HTTPRouteRule, match gwapiv1.HTTPRouteMatch)
- func AddIngressRule(ingress *netv1.Ingress, rule *netv1.IngressRule)
- func AddIngressRulePath(rule *netv1.IngressRule, path netv1.HTTPIngressPath)
- func AddIngressTLS(ingress *netv1.Ingress, tls netv1.IngressTLS)
- func AddLabel(obj metav1.Object, key, value string)
- func AddNamespaceFinalizer(ns *corev1.Namespace, finalizer corev1.FinalizerName)
- func AddNetworkPolicyEgressPeer(rule *netv1.NetworkPolicyEgressRule, peer netv1.NetworkPolicyPeer)
- func AddNetworkPolicyEgressPort(rule *netv1.NetworkPolicyEgressRule, port netv1.NetworkPolicyPort)
- func AddNetworkPolicyEgressRule(np *netv1.NetworkPolicy, rule netv1.NetworkPolicyEgressRule)
- func AddNetworkPolicyIngressPeer(rule *netv1.NetworkPolicyIngressRule, peer netv1.NetworkPolicyPeer)
- func AddNetworkPolicyIngressPort(rule *netv1.NetworkPolicyIngressRule, port netv1.NetworkPolicyPort)
- func AddNetworkPolicyIngressRule(np *netv1.NetworkPolicy, rule netv1.NetworkPolicyIngressRule)
- func AddNetworkPolicyPolicyType(np *netv1.NetworkPolicy, t netv1.PolicyType)
- func AddPVCAccessMode(pvc *corev1.PersistentVolumeClaim, mode corev1.PersistentVolumeAccessMode)
- func AddPodSpecContainer(spec *corev1.PodSpec, container *corev1.Container)
- func AddPodSpecEphemeralContainer(spec *corev1.PodSpec, container *corev1.EphemeralContainer)
- func AddPodSpecImagePullSecret(spec *corev1.PodSpec, secret *corev1.LocalObjectReference)
- func AddPodSpecInitContainer(spec *corev1.PodSpec, container *corev1.Container)
- func AddPodSpecToleration(spec *corev1.PodSpec, toleration *corev1.Toleration)
- func AddPodSpecTopologySpreadConstraints(spec *corev1.PodSpec, constraint *corev1.TopologySpreadConstraint)
- func AddPodSpecVolume(spec *corev1.PodSpec, volume *corev1.Volume)
- func AddResourceClaim(rr *corev1.ResourceRequirements, claim corev1.ResourceClaim)
- func AddRoleBindingSubject(rb *rbacv1.RoleBinding, subject rbacv1.Subject)
- func AddRoleRule(role *rbacv1.Role, rule rbacv1.PolicyRule)
- func AddServiceAccountImagePullSecret(sa *corev1.ServiceAccount, secret corev1.LocalObjectReference)
- func AddServiceAccountSecret(sa *corev1.ServiceAccount, secret corev1.ObjectReference)
- func AddServiceExternalIP(service *corev1.Service, ip string)
- func AddServiceLoadBalancerSourceRange(svc *corev1.Service, cidr string)
- func AddServicePort(service *corev1.Service, port corev1.ServicePort)
- func AddStatefulSetVolumeClaimTemplate(sts *appsv1.StatefulSet, pvc corev1.PersistentVolumeClaim)
- func BaselinePodSecurityContext() *corev1.PodSecurityContext
- func BaselineSecurityContext() *corev1.SecurityContext
- func Create[T any, PT interface{ ... }](name, namespace string) PT
- func CreateAPIService(name string) *apiregistrationv1.APIService
- func CreateBackendTLSPolicy(name, namespace string) *gatewayapiv1.BackendTLSPolicy
- func CreateBinding(name, namespace string) *corev1.Binding
- func CreateCSIDriver(name string) *storagev1.CSIDriver
- func CreateCSINode(name string) *storagev1.CSINode
- func CreateCSIStorageCapacity(name, namespace string) *storagev1.CSIStorageCapacity
- func CreateClusterRole(name string) *rbacv1.ClusterRole
- func CreateClusterRoleBinding(name string) *rbacv1.ClusterRoleBinding
- func CreateComponentStatus(name string) *corev1.ComponentStatus
- func CreateConfigMap(name, namespace string) *corev1.ConfigMap
- func CreateControllerRevision(name, namespace string) *appsv1.ControllerRevision
- func CreateCronJob(name, namespace string) *batchv1.CronJob
- func CreateCustomResourceDefinition(name string) *apiextensionsv1.CustomResourceDefinition
- func CreateDaemonSet(name, namespace string) *appsv1.DaemonSet
- func CreateDeployment(name, namespace string) *appsv1.Deployment
- func CreateEndpointSlice(name, namespace string) *discoveryv1.EndpointSlice
- func CreateEndpoints(name, namespace string) *corev1.Endpoints
- func CreateEvent(name, namespace string) *corev1.Event
- func CreateEviction(name, namespace string) *policyv1.Eviction
- func CreateGRPCRoute(name, namespace string) *gatewayapiv1.GRPCRoute
- func CreateGateway(name, namespace string) *gatewayapiv1.Gateway
- func CreateGatewayClass(name string) *gatewayapiv1.GatewayClass
- func CreateHTTPRoute(name, namespace string) *gatewayapiv1.HTTPRoute
- func CreateHorizontalPodAutoscaler(name, namespace string) *autoscalingv2.HorizontalPodAutoscaler
- func CreateIPAddress(name string) *networkingv1.IPAddress
- func CreateIngress(name, namespace string) *networkingv1.Ingress
- func CreateIngressClass(name string) *networkingv1.IngressClass
- func CreateIngressPath(path string, pathType *netv1.PathType, servicename string, ...) netv1.HTTPIngressPath
- func CreateJob(name, namespace string) *batchv1.Job
- func CreateLease(name, namespace string) *coordinationv1.Lease
- func CreateLimitRange(name, namespace string) *corev1.LimitRange
- func CreateListenerSet(name, namespace string) *gatewayapiv1.ListenerSet
- func CreateMutatingAdmissionPolicy(name string) *admissionregistrationv1.MutatingAdmissionPolicy
- func CreateMutatingAdmissionPolicyBinding(name string) *admissionregistrationv1.MutatingAdmissionPolicyBinding
- func CreateMutatingWebhookConfiguration(name string) *admissionregistrationv1.MutatingWebhookConfiguration
- func CreateNamespace(name string) *corev1.Namespace
- func CreateNetworkPolicy(name, namespace string) *networkingv1.NetworkPolicy
- func CreateNode(name string) *corev1.Node
- func CreatePersistentVolume(name string) *corev1.PersistentVolume
- func CreatePersistentVolumeClaim(name, namespace string) *corev1.PersistentVolumeClaim
- func CreatePod(name, namespace string) *corev1.Pod
- func CreatePodDisruptionBudget(name, namespace string) *policyv1.PodDisruptionBudget
- func CreatePodTemplate(name, namespace string) *corev1.PodTemplate
- func CreatePriorityClass(name string) *schedulingv1.PriorityClass
- func CreateRangeAllocation(name string) *corev1.RangeAllocation
- func CreateReferenceGrant(name, namespace string) *gatewayapiv1.ReferenceGrant
- func CreateReplicaSet(name, namespace string) *appsv1.ReplicaSet
- func CreateReplicationController(name, namespace string) *corev1.ReplicationController
- func CreateResourceQuota(name, namespace string) *corev1.ResourceQuota
- func CreateResourceRequirements() *corev1.ResourceRequirements
- func CreateRole(name, namespace string) *rbacv1.Role
- func CreateRoleBinding(name, namespace string) *rbacv1.RoleBinding
- func CreateRuntimeClass(name string) *nodev1.RuntimeClass
- func CreateSecret(name, namespace string) *corev1.Secret
- func CreateService(name, namespace string) *corev1.Service
- func CreateServiceAccount(name, namespace string) *corev1.ServiceAccount
- func CreateServiceCIDR(name string) *networkingv1.ServiceCIDR
- func CreateStatefulSet(name, namespace string) *appsv1.StatefulSet
- func CreateStorageClass(name string) *storagev1.StorageClass
- func CreateTCPRoute(name, namespace string) *gatewayapiv1.TCPRoute
- func CreateTLSRoute(name, namespace string) *gatewayapiv1.TLSRoute
- func CreateUDPRoute(name, namespace string) *gatewayapiv1.UDPRoute
- func CreateValidatingAdmissionPolicy(name string) *admissionregistrationv1.ValidatingAdmissionPolicy
- func CreateValidatingAdmissionPolicyBinding(name string) *admissionregistrationv1.ValidatingAdmissionPolicyBinding
- func CreateValidatingWebhookConfiguration(name string) *admissionregistrationv1.ValidatingWebhookConfiguration
- func CreateVolumeAttachment(name string) *storagev1.VolumeAttachment
- func CreateVolumeAttributesClass(name string) *storagev1.VolumeAttributesClass
- func GetGroupVersionKind(obj runtime.Object) (schema.GroupVersionKind, error)
- func IsGVKAllowed(gvk schema.GroupVersionKind, allowed []schema.GroupVersionKind) bool
- func IsNamespaced(apiVersion, kind string) (namespaced, known bool)
- func PSALabels(enforce, warn, audit PSALevel, version string) map[string]string
- func PodSecurityContextForLevel(level PSALevel) (*corev1.PodSecurityContext, error)
- func PrivilegedPodSecurityContext() *corev1.PodSecurityContext
- func PrivilegedSecurityContext() *corev1.SecurityContext
- func RegisterSchemes() error
- func RestrictedPodSecurityContext() *corev1.PodSecurityContext
- func RestrictedSecurityContext() *corev1.SecurityContext
- func SecurityContextForLevel(level PSALevel) (*corev1.SecurityContext, error)
- func SetAnnotations(obj metav1.Object, annotations map[string]string)
- func SetConfigMapImmutable(cm *corev1.ConfigMap, immutable bool)
- func SetContainerLifecycle(container *corev1.Container, lifecycle *corev1.Lifecycle)
- func SetContainerLivenessProbe(container *corev1.Container, livenessProbe corev1.Probe)
- func SetContainerReadinessProbe(container *corev1.Container, readinessProbe corev1.Probe)
- func SetContainerSecurityContext(container *corev1.Container, securityContext corev1.SecurityContext)
- func SetContainerStartupProbe(container *corev1.Container, startupProbe corev1.Probe)
- func SetCronJobFailedJobsHistoryLimit(cron *batchv1.CronJob, limit int32)
- func SetCronJobStartingDeadlineSeconds(cron *batchv1.CronJob, sec int64)
- func SetCronJobSuccessfulJobsHistoryLimit(cron *batchv1.CronJob, limit int32)
- func SetCronJobSuspend(cron *batchv1.CronJob, suspend bool)
- func SetCronJobTimeZone(cron *batchv1.CronJob, tz *string)
- func SetDaemonSetRevisionHistoryLimit(ds *appsv1.DaemonSet, limit *int32)
- func SetDeploymentProgressDeadlineSeconds(deployment *appsv1.Deployment, secs int32)
- func SetDeploymentReplicas(deployment *appsv1.Deployment, replicas int32)
- func SetDeploymentRevisionHistoryLimit(deployment *appsv1.Deployment, limit int32)
- func SetHPABehavior(hpa *autoscalingv2.HorizontalPodAutoscaler, ...)
- func SetHPAMinMaxReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, min, max int32)
- func SetHPAScaleTargetRef(hpa *autoscalingv2.HorizontalPodAutoscaler, apiVersion, kind, name string)
- func SetIngressClassName(ingress *netv1.Ingress, class string)
- func SetIngressDefaultBackend(ingress *netv1.Ingress, backend netv1.IngressBackend)
- func SetJobActiveDeadlineSeconds(job *batchv1.Job, secs *int64)
- func SetJobBackoffLimit(job *batchv1.Job, limit int32)
- func SetJobCompletions(job *batchv1.Job, completions int32)
- func SetJobParallelism(job *batchv1.Job, parallelism int32)
- func SetJobTTLSecondsAfterFinished(job *batchv1.Job, ttl int32)
- func SetLabels(obj metav1.Object, labels map[string]string)
- func SetPDBMaxUnavailable(pdb *policyv1.PodDisruptionBudget, val intstr.IntOrString)
- func SetPDBMinAvailable(pdb *policyv1.PodDisruptionBudget, val intstr.IntOrString)
- func SetPDBSelector(pdb *policyv1.PodDisruptionBudget, selector *metav1.LabelSelector)
- func SetPVCDataSource(pvc *corev1.PersistentVolumeClaim, src *corev1.TypedLocalObjectReference)
- func SetPVCDataSourceRef(pvc *corev1.PersistentVolumeClaim, src *corev1.TypedObjectReference)
- func SetPVCSelector(pvc *corev1.PersistentVolumeClaim, selector *metav1.LabelSelector)
- func SetPVCStorageClassName(pvc *corev1.PersistentVolumeClaim, class string)
- func SetPVCVolumeMode(pvc *corev1.PersistentVolumeClaim, mode corev1.PersistentVolumeMode)
- func SetPodSpecAffinity(spec *corev1.PodSpec, aff *corev1.Affinity)
- func SetPodSpecDNSConfig(spec *corev1.PodSpec, cfg *corev1.PodDNSConfig)
- func SetPodSpecSecurityContext(spec *corev1.PodSpec, sc *corev1.PodSecurityContext)
- func SetPodSpecTerminationGracePeriod(spec *corev1.PodSpec, secs int64)
- func SetResourceLimit(rr *corev1.ResourceRequirements, name corev1.ResourceName, ...)
- func SetResourceRequest(rr *corev1.ResourceRequirements, name corev1.ResourceName, ...)
- func SetServiceAccountAutomountToken(sa *corev1.ServiceAccount, automount bool)
- func SetServiceAllocateLoadBalancerNodePorts(svc *corev1.Service, allocate bool)
- func SetServiceIPFamilyPolicy(svc *corev1.Service, policy *corev1.IPFamilyPolicy)
- func SetServiceInternalTrafficPolicy(svc *corev1.Service, policy *corev1.ServiceInternalTrafficPolicy)
- func SetServiceLoadBalancerClass(service *corev1.Service, class string)
- func SetServiceSessionAffinityConfig(svc *corev1.Service, cfg *corev1.SessionAffinityConfig)
- func SetStatefulSetReplicas(sts *appsv1.StatefulSet, replicas int32)
- func SetStatefulSetRevisionHistoryLimit(sts *appsv1.StatefulSet, limit *int32)
- func ToClientObject(obj client.Object) *client.Object
- func ValidateContainerPSA(container *corev1.Container, level PSALevel) error
- func ValidatePackageRef(p *schema.GroupVersionKind) error
- func ValidatePodSpecPSA(spec *corev1.PodSpec, level PSALevel) error
- type FieldMaturity
- type KindInfo
- type Maturity
- type PSALevel
- type ScopeSource
Examples ¶
- Package (ArchitectureRBAC)
- Package (BuilderContractGeneric)
- Package (BuilderContractNamespace)
- Package (BuilderContractStrategy)
- Package (LibraryUsageCreate)
- Package (LibraryUsageDomainModel)
- Package (LibraryUsageEncodeDefault)
- Package (LibraryUsageEncodeNone)
- Package (LibraryUsageErrors)
- Package (LibraryUsageFlux)
- Package (LibraryUsageHelpers)
- Package (LibraryUsageKindFor)
- Package (LibraryUsageMaturity)
- Package (LibraryUsageScopeSource)
- Package (LibraryUsageYAML)
- Package (SiteIndex)
- AddConfigMapData
- AddHPACPUMetric
- AddIngressRule
- AddLabel
- AddServicePort
- Create
- CreateCronJob
- CreateDeployment
- CreateJob
- GetGroupVersionKind
- PSALabels
- SetDeploymentReplicas
- SetPDBMaxUnavailable
- SetResourceRequest
- ValidatePodSpecPSA
Constants ¶
This section is empty.
Variables ¶
var ( Scheme = runtime.NewScheme() Codecs = serializer.NewCodecFactory(Scheme) )
Functions ¶
func AddAnnotation ¶
AddAnnotation sets one annotation on obj, initialising the map when it is nil.
func AddClusterRoleBindingSubject ¶
func AddClusterRoleBindingSubject(crb *rbacv1.ClusterRoleBinding, subject rbacv1.Subject)
func AddClusterRoleRule ¶
func AddClusterRoleRule(cr *rbacv1.ClusterRole, rule rbacv1.PolicyRule)
func AddConfigMapBinaryData ¶
AddConfigMapBinaryData inserts a single binary entry into the ConfigMap.
func AddConfigMapData ¶
AddConfigMapData inserts a single key/value pair into the ConfigMap's Data field.
Example ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
certBytes := []byte("-----BEGIN CERTIFICATE-----")
defaults := map[string]string{"log-level": "info"}
cm := kubernetes.CreateConfigMap("my-config", "default")
kubernetes.AddConfigMapData(cm, "key", "value")
kubernetes.AddConfigMapBinaryData(cm, "cert", certBytes)
kubernetes.SetConfigMapImmutable(cm, true)
// Replacing a map wholesale is an assignment, not a helper
cm.Data = map[string]string{"key": "value"}
// Merging one is a loop over the single-key helper
for k, v := range defaults {
kubernetes.AddConfigMapData(cm, k, v)
}
fmt.Println(len(cm.Data), cm.Data["log-level"], *cm.Immutable)
}
Output: 2 info true
func AddContainerEnv ¶
AddContainerEnv appends an environment variable to the container.
func AddContainerEnvFrom ¶
func AddContainerEnvFrom(container *corev1.Container, envFrom corev1.EnvFromSource)
AddContainerEnvFrom appends an EnvFromSource entry to the container.
func AddContainerPort ¶
func AddContainerPort(container *corev1.Container, port corev1.ContainerPort)
AddContainerPort appends a container port to the Ports slice.
func AddContainerVolumeDevice ¶
func AddContainerVolumeDevice(container *corev1.Container, volumeDevice corev1.VolumeDevice)
AddContainerVolumeDevice appends a volume device to the container.
func AddContainerVolumeMount ¶
func AddContainerVolumeMount(container *corev1.Container, volumeMount corev1.VolumeMount)
AddContainerVolumeMount appends a volume mount to the container.
func AddHPACPUMetric ¶
func AddHPACPUMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, targetUtilization int32)
AddHPACPUMetric adds a CPU utilization metric to the HPA. The targetUtilization is a percentage (e.g. 80 means 80%).
Example ¶
package main
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
hpa := kubernetes.CreateHorizontalPodAutoscaler("my-app", "default")
kubernetes.SetHPAScaleTargetRef(hpa, "apps/v1", "Deployment", "my-app")
kubernetes.SetHPAMinMaxReplicas(hpa, 2, 10)
kubernetes.AddHPACPUMetric(hpa, 80)
pdb := kubernetes.CreatePodDisruptionBudget("my-app", "default")
kubernetes.SetPDBMinAvailable(pdb, intstr.FromInt32(2))
kubernetes.SetPDBSelector(pdb, &metav1.LabelSelector{MatchLabels: map[string]string{"app": "my-app"}})
fmt.Println(*hpa.Spec.MinReplicas, hpa.Spec.MaxReplicas, *hpa.Spec.Metrics[0].Resource.Target.AverageUtilization, pdb.Spec.MinAvailable.IntValue())
}
Output: 2 10 80 2
func AddHPACustomMetric ¶
func AddHPACustomMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, metric autoscalingv2.MetricSpec)
AddHPACustomMetric adds a caller-defined MetricSpec to the HPA. Use this for pod metrics, object metrics, or external metrics that are not covered by the built-in CPU and memory helpers.
func AddHPAMemoryMetric ¶
func AddHPAMemoryMetric(hpa *autoscalingv2.HorizontalPodAutoscaler, targetUtilization int32)
AddHPAMemoryMetric adds a memory utilization metric to the HPA. The targetUtilization is a percentage (e.g. 70 means 70%).
func AddHTTPRouteHostname ¶
AddHTTPRouteHostname appends a hostname to the HTTPRoute.
func AddHTTPRouteParentRef ¶
func AddHTTPRouteParentRef(route *gwapiv1.HTTPRoute, ref gwapiv1.ParentReference)
AddHTTPRouteParentRef appends a parent reference (typically a Gateway) to the HTTPRoute.
func AddHTTPRouteRule ¶
func AddHTTPRouteRule(route *gwapiv1.HTTPRoute, rule gwapiv1.HTTPRouteRule)
AddHTTPRouteRule appends a routing rule to the HTTPRoute.
func AddHTTPRouteRuleBackendRef ¶
func AddHTTPRouteRuleBackendRef(rule *gwapiv1.HTTPRouteRule, ref gwapiv1.HTTPBackendRef)
AddHTTPRouteRuleBackendRef appends a backend reference to an HTTPRouteRule.
func AddHTTPRouteRuleFilter ¶
func AddHTTPRouteRuleFilter(rule *gwapiv1.HTTPRouteRule, filter gwapiv1.HTTPRouteFilter)
AddHTTPRouteRuleFilter appends a filter to an HTTPRouteRule.
func AddHTTPRouteRuleMatch ¶
func AddHTTPRouteRuleMatch(rule *gwapiv1.HTTPRouteRule, match gwapiv1.HTTPRouteMatch)
AddHTTPRouteRuleMatch appends a match condition to an HTTPRouteRule.
func AddIngressRule ¶
func AddIngressRule(ingress *netv1.Ingress, rule *netv1.IngressRule)
AddIngressRule appends an IngressRule to the Ingress spec.
Example ¶
package main
import (
"fmt"
netv1 "k8s.io/api/networking/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
ing := kubernetes.CreateIngress("my-app", "default")
kubernetes.SetIngressClassName(ing, "nginx")
rule := &netv1.IngressRule{Host: "app.example.com"}
pt := netv1.PathTypePrefix
path := kubernetes.CreateIngressPath("/", &pt, "my-app", "http")
kubernetes.AddIngressRulePath(rule, path)
kubernetes.AddIngressRule(ing, rule)
kubernetes.AddIngressTLS(ing, netv1.IngressTLS{Hosts: []string{"app.example.com"}, SecretName: "my-app-tls"})
fmt.Println(*ing.Spec.IngressClassName, ing.Spec.Rules[0].Host, ing.Spec.Rules[0].HTTP.Paths[0].Backend.Service.Name)
}
Output: nginx app.example.com my-app
func AddIngressRulePath ¶
func AddIngressRulePath(rule *netv1.IngressRule, path netv1.HTTPIngressPath)
AddIngressRulePath appends a path to an IngressRule's HTTP paths.
func AddIngressTLS ¶
func AddIngressTLS(ingress *netv1.Ingress, tls netv1.IngressTLS)
AddIngressTLS appends a TLS configuration to the Ingress spec.
func AddLabel ¶
AddLabel sets one label on obj, initialising the map when it is nil.
Example ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
obj := kubernetes.CreateDeployment("web", "default")
kubernetes.SetLabels(obj, map[string]string{"app": "web"})
kubernetes.AddLabel(obj, "tier", "frontend") // initialises a nil map
kubernetes.SetAnnotations(obj, map[string]string{"owner": "platform"})
kubernetes.AddAnnotation(obj, "note", "rotated 2026-09")
fmt.Println(obj.Labels["app"], obj.Labels["tier"], obj.Annotations["note"])
}
Output: web frontend rotated 2026-09
func AddNamespaceFinalizer ¶
func AddNamespaceFinalizer(ns *corev1.Namespace, finalizer corev1.FinalizerName)
AddNamespaceFinalizer appends a finalizer to the Namespace spec.
func AddNetworkPolicyEgressPeer ¶
func AddNetworkPolicyEgressPeer(rule *netv1.NetworkPolicyEgressRule, peer netv1.NetworkPolicyPeer)
AddNetworkPolicyEgressPeer appends a peer to an egress rule's To list.
func AddNetworkPolicyEgressPort ¶
func AddNetworkPolicyEgressPort(rule *netv1.NetworkPolicyEgressRule, port netv1.NetworkPolicyPort)
AddNetworkPolicyEgressPort appends a port to an egress rule.
func AddNetworkPolicyEgressRule ¶
func AddNetworkPolicyEgressRule(np *netv1.NetworkPolicy, rule netv1.NetworkPolicyEgressRule)
AddNetworkPolicyEgressRule appends an egress rule to the NetworkPolicy.
func AddNetworkPolicyIngressPeer ¶
func AddNetworkPolicyIngressPeer(rule *netv1.NetworkPolicyIngressRule, peer netv1.NetworkPolicyPeer)
AddNetworkPolicyIngressPeer appends a peer to an ingress rule's From list.
func AddNetworkPolicyIngressPort ¶
func AddNetworkPolicyIngressPort(rule *netv1.NetworkPolicyIngressRule, port netv1.NetworkPolicyPort)
AddNetworkPolicyIngressPort appends a port to an ingress rule.
func AddNetworkPolicyIngressRule ¶
func AddNetworkPolicyIngressRule(np *netv1.NetworkPolicy, rule netv1.NetworkPolicyIngressRule)
AddNetworkPolicyIngressRule appends an ingress rule to the NetworkPolicy.
func AddNetworkPolicyPolicyType ¶
func AddNetworkPolicyPolicyType(np *netv1.NetworkPolicy, t netv1.PolicyType)
AddNetworkPolicyPolicyType appends a policy type to the NetworkPolicy.
func AddPVCAccessMode ¶
func AddPVCAccessMode(pvc *corev1.PersistentVolumeClaim, mode corev1.PersistentVolumeAccessMode)
AddPVCAccessMode appends an access mode to the claim.
func AddPodSpecContainer ¶
AddPodSpecContainer appends a container to the PodSpec.
func AddPodSpecEphemeralContainer ¶
func AddPodSpecEphemeralContainer(spec *corev1.PodSpec, container *corev1.EphemeralContainer)
AddPodSpecEphemeralContainer appends an ephemeral container to the PodSpec.
func AddPodSpecImagePullSecret ¶
func AddPodSpecImagePullSecret(spec *corev1.PodSpec, secret *corev1.LocalObjectReference)
AddPodSpecImagePullSecret appends an image pull secret to the PodSpec.
func AddPodSpecInitContainer ¶
AddPodSpecInitContainer appends an init container to the PodSpec.
func AddPodSpecToleration ¶
func AddPodSpecToleration(spec *corev1.PodSpec, toleration *corev1.Toleration)
AddPodSpecToleration appends a toleration to the PodSpec.
func AddPodSpecTopologySpreadConstraints ¶
func AddPodSpecTopologySpreadConstraints(spec *corev1.PodSpec, constraint *corev1.TopologySpreadConstraint)
AddPodSpecTopologySpreadConstraints appends a topology spread constraint to the PodSpec.
func AddPodSpecVolume ¶
AddPodSpecVolume appends a volume to the PodSpec.
func AddResourceClaim ¶
func AddResourceClaim(rr *corev1.ResourceRequirements, claim corev1.ResourceClaim)
AddResourceClaim appends a ResourceClaim to the ResourceRequirements.
func AddRoleBindingSubject ¶
func AddRoleBindingSubject(rb *rbacv1.RoleBinding, subject rbacv1.Subject)
func AddRoleRule ¶
func AddRoleRule(role *rbacv1.Role, rule rbacv1.PolicyRule)
func AddServiceAccountImagePullSecret ¶
func AddServiceAccountImagePullSecret(sa *corev1.ServiceAccount, secret corev1.LocalObjectReference)
func AddServiceAccountSecret ¶
func AddServiceAccountSecret(sa *corev1.ServiceAccount, secret corev1.ObjectReference)
func AddServiceExternalIP ¶
AddServiceExternalIP appends an external IP address to the Service spec.
func AddServiceLoadBalancerSourceRange ¶
AddServiceLoadBalancerSourceRange appends a CIDR to the allowed source ranges for a load balancer Service.
func AddServicePort ¶
func AddServicePort(service *corev1.Service, port corev1.ServicePort)
AddServicePort appends a port to the Service spec.
Example ¶
package main
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
svc := kubernetes.CreateService("my-app", "default")
svc.Spec.Selector = map[string]string{"app": "my-app"}
kubernetes.AddServicePort(svc, corev1.ServicePort{Name: "http", Port: 80, TargetPort: intstr.FromInt32(8080)})
svc.Spec.Type = corev1.ServiceTypeLoadBalancer
kubernetes.AddAnnotation(svc, "external-dns.alpha.kubernetes.io/hostname", "app.example.com")
fmt.Println(svc.Spec.Ports[0].Port, svc.Spec.Ports[0].TargetPort.IntValue(), svc.Spec.Type)
}
Output: 80 8080 LoadBalancer
func AddStatefulSetVolumeClaimTemplate ¶
func AddStatefulSetVolumeClaimTemplate(sts *appsv1.StatefulSet, pvc corev1.PersistentVolumeClaim)
AddStatefulSetVolumeClaimTemplate appends a PVC template to the StatefulSet.
func BaselinePodSecurityContext ¶
func BaselinePodSecurityContext() *corev1.PodSecurityContext
BaselinePodSecurityContext returns a PodSecurityContext compliant with the baseline Pod Security Standards level.
func BaselineSecurityContext ¶
func BaselineSecurityContext() *corev1.SecurityContext
BaselineSecurityContext returns a container SecurityContext compliant with the baseline Pod Security Standards level. It disallows privilege escalation and sets SeccompProfile to RuntimeDefault.
func Create ¶
Create allocates a registered Kubernetes object of type T and sets its identity — nothing else.
It resolves TypeMeta (apiVersion, kind) from the package scheme, the same mechanism GetGroupVersionKind uses, and sets metadata.name and metadata.namespace. Every other field is left at its Go zero value: no labels, no annotations, no selector, no defaults. The upstream struct is the construction API for everything else:
d := kubernetes.Create[appsv1.Deployment]("web", "default")
d.Spec.Replicas = ptr.To(int32(3))
PT is inferred from T (core-type inference), so the one-argument call form above is the normal spelling. Cluster-scoped kinds pass "" for namespace. The generated per-kind wrappers (CreateDeployment, CreateNamespace, …) are one-line calls to Create with the scope baked into the signature.
Create panics when T is not registered in the scheme: an unregistered type is a programming error, the same rule the sugar helpers apply to nil receivers.
Example ¶
package main
import (
"fmt"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
d := kubernetes.Create[appsv1.Deployment]("web", "default")
ns := kubernetes.Create[corev1.Namespace]("platform", "") // cluster-scoped: pass ""
fmt.Println(d.APIVersion, d.Kind, ns.APIVersion, ns.Kind)
}
Output: apps/v1 Deployment v1 Namespace
func CreateAPIService ¶
func CreateAPIService(name string) *apiregistrationv1.APIService
CreateAPIService returns a cluster-scoped apiregistration.k8s.io/v1 APIService carrying TypeMeta and identity only.
func CreateBackendTLSPolicy ¶
func CreateBackendTLSPolicy(name, namespace string) *gatewayapiv1.BackendTLSPolicy
CreateBackendTLSPolicy returns a gateway.networking.k8s.io/v1 BackendTLSPolicy carrying TypeMeta and identity only.
func CreateBinding ¶
CreateBinding returns a v1 Binding carrying TypeMeta and identity only.
func CreateCSIDriver ¶
CreateCSIDriver returns a cluster-scoped storage.k8s.io/v1 CSIDriver carrying TypeMeta and identity only.
func CreateCSINode ¶
CreateCSINode returns a cluster-scoped storage.k8s.io/v1 CSINode carrying TypeMeta and identity only.
func CreateCSIStorageCapacity ¶
func CreateCSIStorageCapacity(name, namespace string) *storagev1.CSIStorageCapacity
CreateCSIStorageCapacity returns a storage.k8s.io/v1 CSIStorageCapacity carrying TypeMeta and identity only.
func CreateClusterRole ¶
func CreateClusterRole(name string) *rbacv1.ClusterRole
CreateClusterRole returns a cluster-scoped rbac.authorization.k8s.io/v1 ClusterRole carrying TypeMeta and identity only.
func CreateClusterRoleBinding ¶
func CreateClusterRoleBinding(name string) *rbacv1.ClusterRoleBinding
CreateClusterRoleBinding returns a cluster-scoped rbac.authorization.k8s.io/v1 ClusterRoleBinding carrying TypeMeta and identity only.
func CreateComponentStatus ¶
func CreateComponentStatus(name string) *corev1.ComponentStatus
CreateComponentStatus returns a cluster-scoped v1 ComponentStatus carrying TypeMeta and identity only.
func CreateConfigMap ¶
CreateConfigMap returns a v1 ConfigMap carrying TypeMeta and identity only.
func CreateControllerRevision ¶
func CreateControllerRevision(name, namespace string) *appsv1.ControllerRevision
CreateControllerRevision returns a apps/v1 ControllerRevision carrying TypeMeta and identity only.
func CreateCronJob ¶
CreateCronJob returns a batch/v1 CronJob carrying TypeMeta and identity only.
Example ¶
package main
import (
"fmt"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
cj := kubernetes.CreateCronJob("my-job", "default")
cj.Spec.Schedule = "*/5 * * * *"
cj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever
kubernetes.AddPodSpecContainer(&cj.Spec.JobTemplate.Spec.Template.Spec,
&corev1.Container{Name: "worker", Image: "busybox:1.36"})
cj.Spec.ConcurrencyPolicy = batchv1.ForbidConcurrent
fmt.Println(cj.Spec.Schedule, cj.Spec.ConcurrencyPolicy)
}
Output: */5 * * * * Forbid
func CreateCustomResourceDefinition ¶
func CreateCustomResourceDefinition(name string) *apiextensionsv1.CustomResourceDefinition
CreateCustomResourceDefinition returns a cluster-scoped apiextensions.k8s.io/v1 CustomResourceDefinition carrying TypeMeta and identity only.
func CreateDaemonSet ¶
CreateDaemonSet returns a apps/v1 DaemonSet carrying TypeMeta and identity only.
func CreateDeployment ¶
func CreateDeployment(name, namespace string) *appsv1.Deployment
CreateDeployment returns a apps/v1 Deployment carrying TypeMeta and identity only.
Example ¶
package main
import (
"fmt"
"k8s.io/utils/ptr"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
d := kubernetes.CreateDeployment("web", "default")
d.Spec.Replicas = ptr.To[int32](3)
d.Spec.Template.Spec.ServiceAccountName = "web"
fmt.Println(d.Kind, *d.Spec.Replicas, d.Spec.Template.Spec.ServiceAccountName)
}
Output: Deployment 3 web
func CreateEndpointSlice ¶
func CreateEndpointSlice(name, namespace string) *discoveryv1.EndpointSlice
CreateEndpointSlice returns a discovery.k8s.io/v1 EndpointSlice carrying TypeMeta and identity only.
func CreateEndpoints ¶
CreateEndpoints returns a v1 Endpoints carrying TypeMeta and identity only.
func CreateEvent ¶
CreateEvent returns a v1 Event carrying TypeMeta and identity only.
func CreateEviction ¶
CreateEviction returns a policy/v1 Eviction carrying TypeMeta and identity only.
func CreateGRPCRoute ¶
func CreateGRPCRoute(name, namespace string) *gatewayapiv1.GRPCRoute
CreateGRPCRoute returns a gateway.networking.k8s.io/v1 GRPCRoute carrying TypeMeta and identity only.
func CreateGateway ¶
func CreateGateway(name, namespace string) *gatewayapiv1.Gateway
CreateGateway returns a gateway.networking.k8s.io/v1 Gateway carrying TypeMeta and identity only.
func CreateGatewayClass ¶
func CreateGatewayClass(name string) *gatewayapiv1.GatewayClass
CreateGatewayClass returns a cluster-scoped gateway.networking.k8s.io/v1 GatewayClass carrying TypeMeta and identity only.
func CreateHTTPRoute ¶
func CreateHTTPRoute(name, namespace string) *gatewayapiv1.HTTPRoute
CreateHTTPRoute returns a gateway.networking.k8s.io/v1 HTTPRoute carrying TypeMeta and identity only.
func CreateHorizontalPodAutoscaler ¶
func CreateHorizontalPodAutoscaler(name, namespace string) *autoscalingv2.HorizontalPodAutoscaler
CreateHorizontalPodAutoscaler returns a autoscaling/v2 HorizontalPodAutoscaler carrying TypeMeta and identity only.
func CreateIPAddress ¶
func CreateIPAddress(name string) *networkingv1.IPAddress
CreateIPAddress returns a cluster-scoped networking.k8s.io/v1 IPAddress carrying TypeMeta and identity only.
func CreateIngress ¶
func CreateIngress(name, namespace string) *networkingv1.Ingress
CreateIngress returns a networking.k8s.io/v1 Ingress carrying TypeMeta and identity only.
func CreateIngressClass ¶
func CreateIngressClass(name string) *networkingv1.IngressClass
CreateIngressClass returns a cluster-scoped networking.k8s.io/v1 IngressClass carrying TypeMeta and identity only.
func CreateIngressPath ¶
func CreateIngressPath(path string, pathType *netv1.PathType, servicename string, serviceportname string) netv1.HTTPIngressPath
CreateIngressPath creates an HTTPIngressPath with the given path, path type, service name, and service port name.
func CreateJob ¶
CreateJob returns a batch/v1 Job carrying TypeMeta and identity only.
Example ¶
package main
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
job := kubernetes.CreateJob("migrate", "default")
job.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever
kubernetes.AddPodSpecContainer(&job.Spec.Template.Spec,
&corev1.Container{Name: "migrate", Image: "busybox:1.36"})
fmt.Println(job.Spec.Template.Spec.RestartPolicy, job.Spec.Template.Spec.Containers[0].Name)
}
Output: Never migrate
func CreateLease ¶
func CreateLease(name, namespace string) *coordinationv1.Lease
CreateLease returns a coordination.k8s.io/v1 Lease carrying TypeMeta and identity only.
func CreateLimitRange ¶
func CreateLimitRange(name, namespace string) *corev1.LimitRange
CreateLimitRange returns a v1 LimitRange carrying TypeMeta and identity only.
func CreateListenerSet ¶
func CreateListenerSet(name, namespace string) *gatewayapiv1.ListenerSet
CreateListenerSet returns a gateway.networking.k8s.io/v1 ListenerSet carrying TypeMeta and identity only.
func CreateMutatingAdmissionPolicy ¶
func CreateMutatingAdmissionPolicy(name string) *admissionregistrationv1.MutatingAdmissionPolicy
CreateMutatingAdmissionPolicy returns a cluster-scoped admissionregistration.k8s.io/v1 MutatingAdmissionPolicy carrying TypeMeta and identity only.
func CreateMutatingAdmissionPolicyBinding ¶
func CreateMutatingAdmissionPolicyBinding(name string) *admissionregistrationv1.MutatingAdmissionPolicyBinding
CreateMutatingAdmissionPolicyBinding returns a cluster-scoped admissionregistration.k8s.io/v1 MutatingAdmissionPolicyBinding carrying TypeMeta and identity only.
func CreateMutatingWebhookConfiguration ¶
func CreateMutatingWebhookConfiguration(name string) *admissionregistrationv1.MutatingWebhookConfiguration
CreateMutatingWebhookConfiguration returns a cluster-scoped admissionregistration.k8s.io/v1 MutatingWebhookConfiguration carrying TypeMeta and identity only.
func CreateNamespace ¶
CreateNamespace returns a cluster-scoped v1 Namespace carrying TypeMeta and identity only.
func CreateNetworkPolicy ¶
func CreateNetworkPolicy(name, namespace string) *networkingv1.NetworkPolicy
CreateNetworkPolicy returns a networking.k8s.io/v1 NetworkPolicy carrying TypeMeta and identity only.
func CreateNode ¶
CreateNode returns a cluster-scoped v1 Node carrying TypeMeta and identity only.
func CreatePersistentVolume ¶
func CreatePersistentVolume(name string) *corev1.PersistentVolume
CreatePersistentVolume returns a cluster-scoped v1 PersistentVolume carrying TypeMeta and identity only.
func CreatePersistentVolumeClaim ¶
func CreatePersistentVolumeClaim(name, namespace string) *corev1.PersistentVolumeClaim
CreatePersistentVolumeClaim returns a v1 PersistentVolumeClaim carrying TypeMeta and identity only.
func CreatePodDisruptionBudget ¶
func CreatePodDisruptionBudget(name, namespace string) *policyv1.PodDisruptionBudget
CreatePodDisruptionBudget returns a policy/v1 PodDisruptionBudget carrying TypeMeta and identity only.
func CreatePodTemplate ¶
func CreatePodTemplate(name, namespace string) *corev1.PodTemplate
CreatePodTemplate returns a v1 PodTemplate carrying TypeMeta and identity only.
func CreatePriorityClass ¶
func CreatePriorityClass(name string) *schedulingv1.PriorityClass
CreatePriorityClass returns a cluster-scoped scheduling.k8s.io/v1 PriorityClass carrying TypeMeta and identity only.
func CreateRangeAllocation ¶
func CreateRangeAllocation(name string) *corev1.RangeAllocation
CreateRangeAllocation returns a cluster-scoped v1 RangeAllocation carrying TypeMeta and identity only.
func CreateReferenceGrant ¶
func CreateReferenceGrant(name, namespace string) *gatewayapiv1.ReferenceGrant
CreateReferenceGrant returns a gateway.networking.k8s.io/v1 ReferenceGrant carrying TypeMeta and identity only.
func CreateReplicaSet ¶
func CreateReplicaSet(name, namespace string) *appsv1.ReplicaSet
CreateReplicaSet returns a apps/v1 ReplicaSet carrying TypeMeta and identity only.
func CreateReplicationController ¶
func CreateReplicationController(name, namespace string) *corev1.ReplicationController
CreateReplicationController returns a v1 ReplicationController carrying TypeMeta and identity only.
func CreateResourceQuota ¶
func CreateResourceQuota(name, namespace string) *corev1.ResourceQuota
CreateResourceQuota returns a v1 ResourceQuota carrying TypeMeta and identity only.
func CreateResourceRequirements ¶
func CreateResourceRequirements() *corev1.ResourceRequirements
CreateResourceRequirements returns a ResourceRequirements initialized with empty Requests and Limits maps.
func CreateRole ¶
CreateRole returns a rbac.authorization.k8s.io/v1 Role carrying TypeMeta and identity only.
func CreateRoleBinding ¶
func CreateRoleBinding(name, namespace string) *rbacv1.RoleBinding
CreateRoleBinding returns a rbac.authorization.k8s.io/v1 RoleBinding carrying TypeMeta and identity only.
func CreateRuntimeClass ¶
func CreateRuntimeClass(name string) *nodev1.RuntimeClass
CreateRuntimeClass returns a cluster-scoped node.k8s.io/v1 RuntimeClass carrying TypeMeta and identity only.
func CreateSecret ¶
CreateSecret returns a v1 Secret carrying TypeMeta and identity only.
func CreateService ¶
CreateService returns a v1 Service carrying TypeMeta and identity only.
func CreateServiceAccount ¶
func CreateServiceAccount(name, namespace string) *corev1.ServiceAccount
CreateServiceAccount returns a v1 ServiceAccount carrying TypeMeta and identity only.
func CreateServiceCIDR ¶
func CreateServiceCIDR(name string) *networkingv1.ServiceCIDR
CreateServiceCIDR returns a cluster-scoped networking.k8s.io/v1 ServiceCIDR carrying TypeMeta and identity only.
func CreateStatefulSet ¶
func CreateStatefulSet(name, namespace string) *appsv1.StatefulSet
CreateStatefulSet returns a apps/v1 StatefulSet carrying TypeMeta and identity only.
func CreateStorageClass ¶
func CreateStorageClass(name string) *storagev1.StorageClass
CreateStorageClass returns a cluster-scoped storage.k8s.io/v1 StorageClass carrying TypeMeta and identity only.
func CreateTCPRoute ¶
func CreateTCPRoute(name, namespace string) *gatewayapiv1.TCPRoute
CreateTCPRoute returns a gateway.networking.k8s.io/v1 TCPRoute carrying TypeMeta and identity only.
func CreateTLSRoute ¶
func CreateTLSRoute(name, namespace string) *gatewayapiv1.TLSRoute
CreateTLSRoute returns a gateway.networking.k8s.io/v1 TLSRoute carrying TypeMeta and identity only.
func CreateUDPRoute ¶
func CreateUDPRoute(name, namespace string) *gatewayapiv1.UDPRoute
CreateUDPRoute returns a gateway.networking.k8s.io/v1 UDPRoute carrying TypeMeta and identity only.
func CreateValidatingAdmissionPolicy ¶
func CreateValidatingAdmissionPolicy(name string) *admissionregistrationv1.ValidatingAdmissionPolicy
CreateValidatingAdmissionPolicy returns a cluster-scoped admissionregistration.k8s.io/v1 ValidatingAdmissionPolicy carrying TypeMeta and identity only.
func CreateValidatingAdmissionPolicyBinding ¶
func CreateValidatingAdmissionPolicyBinding(name string) *admissionregistrationv1.ValidatingAdmissionPolicyBinding
CreateValidatingAdmissionPolicyBinding returns a cluster-scoped admissionregistration.k8s.io/v1 ValidatingAdmissionPolicyBinding carrying TypeMeta and identity only.
func CreateValidatingWebhookConfiguration ¶
func CreateValidatingWebhookConfiguration(name string) *admissionregistrationv1.ValidatingWebhookConfiguration
CreateValidatingWebhookConfiguration returns a cluster-scoped admissionregistration.k8s.io/v1 ValidatingWebhookConfiguration carrying TypeMeta and identity only.
func CreateVolumeAttachment ¶
func CreateVolumeAttachment(name string) *storagev1.VolumeAttachment
CreateVolumeAttachment returns a cluster-scoped storage.k8s.io/v1 VolumeAttachment carrying TypeMeta and identity only.
func CreateVolumeAttributesClass ¶
func CreateVolumeAttributesClass(name string) *storagev1.VolumeAttributesClass
CreateVolumeAttributesClass returns a cluster-scoped storage.k8s.io/v1 VolumeAttributesClass carrying TypeMeta and identity only.
func GetGroupVersionKind ¶
func GetGroupVersionKind(obj runtime.Object) (schema.GroupVersionKind, error)
GetGroupVersionKind returns the GroupVersionKind of the given Kubernetes runtime.Object.
Example ¶
package main
import (
"fmt"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
myDeployment := kubernetes.CreateDeployment("web", "default")
allowedGVKs := []schema.GroupVersionKind{appsv1.SchemeGroupVersion.WithKind("Deployment")}
// Lazily registers every supported API group (core K8s, FluxCD, cert-manager, ...)
err := kubernetes.RegisterSchemes()
if err != nil {
panic(err)
}
// Resolve the GVK of any registered runtime.Object
gvk, err := kubernetes.GetGroupVersionKind(myDeployment)
if err != nil {
panic(err)
}
// Check if a GVK is in an allow list
ok := kubernetes.IsGVKAllowed(gvk, allowedGVKs)
fmt.Println(gvk, ok)
}
Output: apps/v1, Kind=Deployment true
func IsGVKAllowed ¶
func IsGVKAllowed(gvk schema.GroupVersionKind, allowed []schema.GroupVersionKind) bool
IsGVKAllowed checks if a given GVK is present in a user-defined allowed set.
func IsNamespaced ¶
IsNamespaced reports whether a registered kind is namespaced, and whether it is registered at all. A caller must distinguish the two: an unregistered kind's scope is unknown, not namespaced.
Unlike KindFor this ignores the version, and deliberately: scope is a property of the resource, uniform across the versions of one group/kind — an apiVersion the API server serves at all serves it at the same scope. A manifest written against an older or newer version of a kind kure registers must still be answered, since the alternative is "unknown" for a scope that is not in doubt.
func PSALabels ¶
PSALabels returns the Pod Security Admission labels for the given modes. It writes nothing; apply the result with AddLabel:
for k, v := range kubernetes.PSALabels(kubernetes.PSARestricted, "", "", "v1.28") {
kubernetes.AddLabel(ns, k, v)
}
An empty level omits that mode's labels; an empty version omits the *-version labels. This is a value helper, not builder sugar — one argument expands into up to six labels, which no Set<Field> helper is allowed to do (see the builder contract in this package's README).
Example ¶
package main
import (
"fmt"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
ns := kubernetes.CreateNamespace("my-app")
kubernetes.AddLabel(ns, "env", "prod")
// enforce, warn, audit; "" skips a mode, version "" omits the version labels
for k, v := range kubernetes.PSALabels(kubernetes.PSARestricted, kubernetes.PSARestricted, kubernetes.PSARestricted, "v1.28") {
kubernetes.AddLabel(ns, k, v)
}
fmt.Println(len(ns.Labels), ns.Labels["pod-security.kubernetes.io/enforce"])
}
Output: 7 restricted
func PodSecurityContextForLevel ¶
func PodSecurityContextForLevel(level PSALevel) (*corev1.PodSecurityContext, error)
PodSecurityContextForLevel returns a PodSecurityContext for the given PSA level.
func PrivilegedPodSecurityContext ¶
func PrivilegedPodSecurityContext() *corev1.PodSecurityContext
PrivilegedPodSecurityContext returns a PodSecurityContext with no restrictions, matching the privileged Pod Security Standards level.
func PrivilegedSecurityContext ¶
func PrivilegedSecurityContext() *corev1.SecurityContext
PrivilegedSecurityContext returns a container SecurityContext with no restrictions, matching the privileged Pod Security Standards level.
func RegisterSchemes ¶
func RegisterSchemes() error
RegisterSchemes adds all Kubernetes and Flux custom resource schemes to Scheme. The registration is performed only once. The first non-nil error returned by any AddToScheme call is cached and returned on subsequent invocations.
func RestrictedPodSecurityContext ¶
func RestrictedPodSecurityContext() *corev1.PodSecurityContext
RestrictedPodSecurityContext returns a PodSecurityContext compliant with the restricted Pod Security Standards level. It sets RunAsNonRoot and configures SeccompProfile to RuntimeDefault.
func RestrictedSecurityContext ¶
func RestrictedSecurityContext() *corev1.SecurityContext
RestrictedSecurityContext returns a container SecurityContext compliant with the restricted Pod Security Standards level. It drops all capabilities, disallows privilege escalation, sets a read-only root filesystem, and configures SeccompProfile to RuntimeDefault.
func SecurityContextForLevel ¶
func SecurityContextForLevel(level PSALevel) (*corev1.SecurityContext, error)
SecurityContextForLevel returns a container SecurityContext for the given PSA level.
func SetAnnotations ¶
SetAnnotations replaces obj's annotations with annotations.
func SetConfigMapImmutable ¶
SetConfigMapImmutable sets the immutable field for the ConfigMap.
func SetContainerLifecycle ¶
func SetContainerLivenessProbe ¶
SetContainerLivenessProbe sets the container's liveness probe.
func SetContainerReadinessProbe ¶
SetContainerReadinessProbe sets the container's readiness probe.
func SetContainerSecurityContext ¶
func SetContainerSecurityContext(container *corev1.Container, securityContext corev1.SecurityContext)
SetContainerSecurityContext sets the security context on the container.
func SetContainerStartupProbe ¶
SetContainerStartupProbe sets the container's startup probe.
func SetCronJobFailedJobsHistoryLimit ¶
SetCronJobFailedJobsHistoryLimit sets the number of failed finished jobs to retain.
func SetCronJobStartingDeadlineSeconds ¶
SetCronJobStartingDeadlineSeconds sets the optional deadline in seconds for starting the job if it misses its scheduled time.
func SetCronJobSuccessfulJobsHistoryLimit ¶
SetCronJobSuccessfulJobsHistoryLimit sets the number of successful finished jobs to retain.
func SetCronJobSuspend ¶
SetCronJobSuspend sets whether the CronJob is suspended.
func SetCronJobTimeZone ¶
SetCronJobTimeZone sets the time zone for the CronJob schedule.
func SetDaemonSetRevisionHistoryLimit ¶
SetDaemonSetRevisionHistoryLimit sets the revision history limit.
func SetDeploymentProgressDeadlineSeconds ¶
func SetDeploymentProgressDeadlineSeconds(deployment *appsv1.Deployment, secs int32)
SetDeploymentProgressDeadlineSeconds sets the progress deadline seconds.
func SetDeploymentReplicas ¶
func SetDeploymentReplicas(deployment *appsv1.Deployment, replicas int32)
SetDeploymentReplicas sets the desired replica count.
Example ¶
package main
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
dep := kubernetes.CreateDeployment("my-app", "default")
kubernetes.AddLabel(dep, "app", "my-app")
dep.Spec.Selector = &metav1.LabelSelector{MatchLabels: map[string]string{"app": "my-app"}}
dep.Spec.Template.Labels = map[string]string{"app": "my-app"}
podSpec := &dep.Spec.Template.Spec
kubernetes.AddPodSpecContainer(podSpec, &corev1.Container{Name: "app", Image: "nginx:1.25"})
kubernetes.AddPodSpecToleration(podSpec, &corev1.Toleration{Key: "dedicated", Value: "web"})
kubernetes.SetDeploymentReplicas(dep, 3)
fmt.Println(podSpec.Containers[0].Image, podSpec.Tolerations[0].Key, *dep.Spec.Replicas)
}
Output: nginx:1.25 dedicated 3
func SetDeploymentRevisionHistoryLimit ¶
func SetDeploymentRevisionHistoryLimit(deployment *appsv1.Deployment, limit int32)
SetDeploymentRevisionHistoryLimit sets the revision history limit.
func SetHPABehavior ¶
func SetHPABehavior(hpa *autoscalingv2.HorizontalPodAutoscaler, behavior *autoscalingv2.HorizontalPodAutoscalerBehavior)
SetHPABehavior sets the scaling behavior for the HPA, controlling scale-up and scale-down stabilization windows and policies.
func SetHPAMinMaxReplicas ¶
func SetHPAMinMaxReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, min, max int32)
SetHPAMinMaxReplicas sets the minimum and maximum replica counts for the HPA.
func SetHPAScaleTargetRef ¶
func SetHPAScaleTargetRef(hpa *autoscalingv2.HorizontalPodAutoscaler, apiVersion, kind, name string)
SetHPAScaleTargetRef sets the scale target reference for the HPA, identifying the resource (e.g. Deployment) that the autoscaler controls.
func SetIngressClassName ¶
SetIngressClassName sets the ingress class name on the Ingress spec.
func SetIngressDefaultBackend ¶
func SetIngressDefaultBackend(ingress *netv1.Ingress, backend netv1.IngressBackend)
SetIngressDefaultBackend sets the default backend on the Ingress spec.
func SetJobActiveDeadlineSeconds ¶
SetJobActiveDeadlineSeconds sets the active deadline seconds for the job.
func SetJobBackoffLimit ¶
func SetJobCompletions ¶
func SetJobParallelism ¶
func SetPDBMaxUnavailable ¶
func SetPDBMaxUnavailable(pdb *policyv1.PodDisruptionBudget, val intstr.IntOrString)
SetPDBMaxUnavailable sets MaxUnavailable. See SetPDBMinAvailable for the mutual exclusion between the two fields.
func SetPDBMinAvailable ¶
func SetPDBMinAvailable(pdb *policyv1.PodDisruptionBudget, val intstr.IntOrString)
SetPDBMinAvailable sets MinAvailable. MinAvailable and MaxUnavailable are mutually exclusive upstream; this helper writes only the field it names, so a caller that sets both produces a PodDisruptionBudget the API server rejects. Clear the other field explicitly when switching:
pdb.Spec.MaxUnavailable = nil kubernetes.SetPDBMinAvailable(pdb, intstr.FromInt32(2))
func SetPDBSelector ¶
func SetPDBSelector(pdb *policyv1.PodDisruptionBudget, selector *metav1.LabelSelector)
SetPDBSelector sets the label selector for the PDB.
func SetPVCDataSource ¶
func SetPVCDataSource(pvc *corev1.PersistentVolumeClaim, src *corev1.TypedLocalObjectReference)
SetPVCDataSource sets the data source for the claim.
func SetPVCDataSourceRef ¶
func SetPVCDataSourceRef(pvc *corev1.PersistentVolumeClaim, src *corev1.TypedObjectReference)
SetPVCDataSourceRef sets the data source reference for the claim.
func SetPVCSelector ¶
func SetPVCSelector(pvc *corev1.PersistentVolumeClaim, selector *metav1.LabelSelector)
SetPVCSelector sets the selector for the claim.
func SetPVCStorageClassName ¶
func SetPVCStorageClassName(pvc *corev1.PersistentVolumeClaim, class string)
SetPVCStorageClassName sets the storage class name for the claim.
func SetPVCVolumeMode ¶
func SetPVCVolumeMode(pvc *corev1.PersistentVolumeClaim, mode corev1.PersistentVolumeMode)
SetPVCVolumeMode sets the volume mode of the claim.
func SetPodSpecAffinity ¶
SetPodSpecAffinity assigns affinity rules to the PodSpec.
func SetPodSpecDNSConfig ¶
func SetPodSpecDNSConfig(spec *corev1.PodSpec, cfg *corev1.PodDNSConfig)
SetPodSpecDNSConfig sets the DNS config.
func SetPodSpecSecurityContext ¶
func SetPodSpecSecurityContext(spec *corev1.PodSpec, sc *corev1.PodSecurityContext)
SetPodSpecSecurityContext sets the security context for the PodSpec.
func SetPodSpecTerminationGracePeriod ¶
SetPodSpecTerminationGracePeriod sets the termination grace period seconds.
func SetResourceLimit ¶
func SetResourceLimit(rr *corev1.ResourceRequirements, name corev1.ResourceName, qty resource.Quantity)
SetResourceLimit sets a named resource limit. Parse the quantity at the call site, as for SetResourceRequest.
func SetResourceRequest ¶
func SetResourceRequest(rr *corev1.ResourceRequirements, name corev1.ResourceName, qty resource.Quantity)
SetResourceRequest sets a named resource request. Parse the quantity at the call site (resource.MustParse("100m") for a literal, resource.ParseQuantity when the text comes from configuration).
Example ¶
package main
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
reqs := kubernetes.CreateResourceRequirements()
kubernetes.SetResourceRequest(reqs, corev1.ResourceCPU, resource.MustParse("100m"))
kubernetes.SetResourceLimit(reqs, corev1.ResourceMemory, resource.MustParse("512Mi"))
fmt.Println(reqs.Requests.Cpu(), reqs.Limits.Memory())
}
Output: 100m 512Mi
func SetServiceAccountAutomountToken ¶
func SetServiceAccountAutomountToken(sa *corev1.ServiceAccount, automount bool)
func SetServiceAllocateLoadBalancerNodePorts ¶
SetServiceAllocateLoadBalancerNodePorts controls whether node ports are allocated for a LoadBalancer Service.
func SetServiceIPFamilyPolicy ¶
func SetServiceIPFamilyPolicy(svc *corev1.Service, policy *corev1.IPFamilyPolicy)
SetServiceIPFamilyPolicy sets the IP family policy on the Service spec.
func SetServiceInternalTrafficPolicy ¶
func SetServiceInternalTrafficPolicy(svc *corev1.Service, policy *corev1.ServiceInternalTrafficPolicy)
SetServiceInternalTrafficPolicy sets the internal traffic policy on the Service spec.
func SetServiceLoadBalancerClass ¶
SetServiceLoadBalancerClass sets the load balancer class on the Service spec.
func SetServiceSessionAffinityConfig ¶
func SetServiceSessionAffinityConfig(svc *corev1.Service, cfg *corev1.SessionAffinityConfig)
SetServiceSessionAffinityConfig configures the session affinity options.
func SetStatefulSetReplicas ¶
func SetStatefulSetReplicas(sts *appsv1.StatefulSet, replicas int32)
SetStatefulSetReplicas sets the replica count.
func SetStatefulSetRevisionHistoryLimit ¶
func SetStatefulSetRevisionHistoryLimit(sts *appsv1.StatefulSet, limit *int32)
SetStatefulSetRevisionHistoryLimit sets the revision history limit.
func ToClientObject ¶
Helper function to convert to client.Object
func ValidateContainerPSA ¶
ValidateContainerPSA checks whether a container's SecurityContext is compliant with the given PSA level. Returns nil when compliant, or a *errors.PSAViolationError describing the first violation found. Field paths are relative to the container (no container prefix).
func ValidatePackageRef ¶
func ValidatePackageRef(p *schema.GroupVersionKind) error
func ValidatePodSpecPSA ¶
ValidatePodSpecPSA checks whether a PodSpec is compliant with the given PSA level. It validates both the pod-level security context and all containers (including init and ephemeral containers). Returns nil when compliant, or a *errors.PSAViolationError describing the first violation found. Field paths are relative to the PodSpec.
Example ¶
package main
import (
"fmt"
corev1 "k8s.io/api/core/v1"
"github.com/go-kure/kure/pkg/kubernetes"
)
func main() {
container := &corev1.Container{Name: "app", Image: "nginx:1.25", SecurityContext: kubernetes.RestrictedSecurityContext()}
podSpec := &corev1.PodSpec{Containers: []corev1.Container{*container}}
psc, err := kubernetes.PodSecurityContextForLevel(kubernetes.PSARestricted)
if err != nil {
panic(err)
}
podSpec.SecurityContext = psc
err = kubernetes.ValidateContainerPSA(container, kubernetes.PSARestricted)
fmt.Println(*container.SecurityContext.RunAsNonRoot, err)
err = kubernetes.ValidatePodSpecPSA(podSpec, kubernetes.PSARestricted)
fmt.Println(err)
}
Output: true <nil> <nil>
Types ¶
type FieldMaturity ¶
type FieldMaturity struct {
ImportPath string // package declaring TypeName
TypeName string // Go type declaring the field
Field string // the field's JSON name, or its Go name when untagged
GoField string // the Go field name
Gates []string // upstream feature gates that must be enabled
Stability Maturity
Module string
ModuleVersion string
}
FieldMaturity is one field, of one type reachable from a registered kind, that upstream gates or documents as less than stable.
kure neither warns nor filters on this. It reports, and a consumer with cluster knowledge decides. The table exists because the failure it describes is silent: for built-in types the API server does not reject a field whose feature gate is disabled, it clears the field and admits the object, so the manifest reads as applied and is not.
Only construction-side fields appear. Status types are excluded: their fields are reported by the cluster, never set by a caller.
func FieldMaturities ¶
func FieldMaturities() []FieldMaturity
FieldMaturities returns every construction-side field of a registered kind that the pinned sources gate or document as less than stable. Status types are not walked; see the package README for why.
A copy, for the reason Kinds gives, and a deep one: each row's Gates slice is copied too, since a shallow copy would hand out rows that still share their gate list with the table.
func GatedFields ¶
func GatedFields() []FieldMaturity
GatedFields returns every field that requires an upstream feature gate. The rows are copies, Gates included.
func MaturityForType ¶
func MaturityForType(importPath, typeName string) []FieldMaturity
MaturityForType returns the maturity entries declared by one Go type. The rows are copies, Gates included.
type KindInfo ¶
type KindInfo struct {
Group string
Version string
Kind string
GoType string // Go type name, without package qualifier
ImportPath string // package declaring GoType
Module string // module providing ImportPath
ModuleVersion string // the version this build pins
Namespaced bool
// ScopeSource names what said so, making a wrong scope traceable to the
// thing that claimed it.
ScopeSource ScopeSource
}
KindInfo describes one object kind registered in Scheme: its group, version and kind, the Go type that implements it, and the pinned module that type came from.
The values live in zz_generated_tables.go, derived from the registered scheme and the upstream +kubebuilder:resource markers. They are plain strings and bools on purpose: the generator writes into this package, so a table that referenced upstream types could not be regenerated after an API bump removed one of them.
func KindByGroupKind ¶
KindByGroupKind returns the registered kind for a "group/Kind" key.
A group/kind registered at more than one version has one row per version, and this returns the first in table order: the lowest version string, which is not necessarily the newest or the stored one. Read from it only what the versions share, which is the scope. Everything else on the row, ScopeSource included, describes that one version: a marker may state the scope of one version's type and the shipped definition that of another. For one version's row, ask KindFor.
func KindFor ¶
KindFor returns the registered kind for an apiVersion and kind, matching the version as well as the group.
The version is part of the match because most of what a KindInfo carries is version-specific: GoType, ImportPath and ModuleVersion describe one version's Go type. Answering an "autoscaling/v1" question with the registered "autoscaling/v2" row would name a type that does not implement the version asked about. A group/kind kure registers at a version other than the one asked for reads as unregistered, which is what it is.
func KindForAnyVersion ¶
KindForAnyVersion returns the registered kind for an apiVersion and kind without requiring the version to be registered: the row for that exact version when kure registers it, and otherwise the row KindByGroupKind returns for the group/kind.
It answers the question whose answer does not vary between the versions of one group/kind: scope. Use KindFor for anything version-specific, since the row this returns may describe a different version than the one asked about; its ScopeSource then says what declared the scope for that version's type.
func Kinds ¶
func Kinds() []KindInfo
Kinds returns every object kind registered in the scheme, with the pinned module its Go type came from and the scope derived from that module.
The returned slice is a copy. The table it comes from is process-global and is read on every lookup, including the ones github.com/go-kure/kure/pkg/manifest answers scope questions with, so a consumer that edited a row in place — to relabel a kind for its own output, say — would change what every later caller in the process is told, at a distance and with nothing to trace it to.
func (KindInfo) APIVersion ¶
APIVersion returns the apiVersion string for the kind: "v1" for the core group, "group/version" otherwise.
type Maturity ¶
type Maturity string
Maturity is what the pinned upstream sources say about a field's stability.
const ( // MaturityStable is the absence of any maturity signal. MaturityStable Maturity = "" // MaturityAlpha is declared by the field's own documentation. MaturityAlpha Maturity = "alpha" // MaturityBeta is declared by the field's own documentation. MaturityBeta Maturity = "beta" // MaturityDeprecated is declared by a "Deprecated:" doc comment. MaturityDeprecated Maturity = "deprecated" )
type PSALevel ¶
type PSALevel string
PSALevel represents the Pod Security Standards level.
const ( // PSARestricted is the most restrictive Pod Security Standards level. // It follows the current best practices for hardening pods. PSARestricted PSALevel = "restricted" // PSABaseline provides a minimally restrictive policy that prevents // known privilege escalations while allowing most workloads. PSABaseline PSALevel = "baseline" // PSAPrivileged is an unrestricted policy providing the widest possible // level of permissions. PSAPrivileged PSALevel = "privileged" )
type ScopeSource ¶
type ScopeSource string
ScopeSource names what declared a kind's scope.
const ( // ScopeSourceMarker is the kind's own +kubebuilder:resource marker in the // module that declares its Go type. ScopeSourceMarker ScopeSource = "marker" // ScopeSourceShippedCRD is the CustomResourceDefinition the kind's module // ships, read when the Go type carries no marker. ScopeSourceShippedCRD ScopeSource = "crd" // ScopeSourceBuiltin is the API server itself: the kinds whose scope is // defined by the Kubernetes API rather than by anything in a module. These // are the built-in kinds, and nothing else is. ScopeSourceBuiltin ScopeSource = "builtin" )
Source Files
¶
- configmap.go
- container.go
- create.go
- cronjob.go
- daemonset.go
- deployment.go
- doc.go
- hpa.go
- httproute.go
- ingress.go
- job.go
- metadata.go
- namespace.go
- networkpolicy.go
- pdb.go
- persistentvolumeclaim.go
- podspec.go
- psa.go
- rbac.go
- resourcerequirements.go
- scheme.go
- service.go
- serviceaccount.go
- statefulset.go
- tables.go
- utilities.go
- zz_generated_create.go
- zz_generated_tables.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package certmanager exposes the generated constructors and the admissible sugar for cert-manager resources: Certificate, Issuer and ClusterIssuer.
|
Package certmanager exposes the generated constructors and the admissible sugar for cert-manager resources: Certificate, Issuer and ClusterIssuer. |
|
Package cilium exposes the generated constructors and the admissible sugar for Cilium resources: the network policies, CIDR groups, egress gateway and local redirect policies, load balancer IP pools, Envoy configs and the BGPv2 kinds.
|
Package cilium exposes the generated constructors and the admissible sugar for Cilium resources: the network policies, CIDR groups, egress gateway and local redirect policies, load balancer IP pools, Envoy configs and the BGPv2 kinds. |
|
Package cnpg exposes the generated constructors and the admissible sugar for CloudNativePG (CNPG) and Barman Cloud plugin resources: Cluster, Database, Pooler, ScheduledBackup, ObjectStore and the image catalogs.
|
Package cnpg exposes the generated constructors and the admissible sugar for CloudNativePG (CNPG) and Barman Cloud plugin resources: Cluster, Database, Pooler, ScheduledBackup, ObjectStore and the image catalogs. |
|
Package externalsecrets exposes the generated constructors and the admissible sugar for External Secrets Operator resources: ExternalSecret, SecretStore and ClusterSecretStore.
|
Package externalsecrets exposes the generated constructors and the admissible sugar for External Secrets Operator resources: ExternalSecret, SecretStore and ClusterSecretStore. |
|
Package fluxcd exposes helper functions for constructing resources used by the Flux family of controllers.
|
Package fluxcd exposes helper functions for constructing resources used by the Flux family of controllers. |
|
internal
|
|
|
admission
Package admission classifies the exported Set*/Add* sugar helpers under pkg/kubernetes by the builder contract's admission classes (ADR-038 §4).
|
Package admission classifies the exported Set*/Add* sugar helpers under pkg/kubernetes by the builder contract's admission classes (ADR-038 §4). |
|
gen
command
Command gen emits the per-kind constructor wrappers under pkg/kubernetes and the kinds registry the identity test walks, from the registered scheme and the scope table in internal/kinds.
|
Command gen emits the per-kind constructor wrappers under pkg/kubernetes and the kinds registry the identity test walks, from the registered scheme and the scope table in internal/kinds. |
|
kinds
Package kinds enumerates the object kinds registered in the pkg/kubernetes scheme and states each one's scope.
|
Package kinds enumerates the object kinds registered in the pkg/kubernetes scheme and states each one's scope. |
|
markers
Package markers parses the controller-gen marker comments that upstream API types carry, so kure derives a kind's scope and a field's maturity from the pinned module sources instead of a hand-kept table.
|
Package markers parses the controller-gen marker comments that upstream API types carry, so kure derives a kind's scope and a field's maturity from the pinned module sources instead of a hand-kept table. |
|
maturity
Package maturity reports which fields of the API types kure builds are gated, alpha, beta or deprecated upstream.
|
Package maturity reports which fields of the API types kure builds are gated, alpha, beta or deprecated upstream. |
|
upstream
Package upstream loads the pinned API module sources that back the registered kinds, so scope and maturity are read from the modules kure actually builds against rather than from a table maintained by hand.
|
Package upstream loads the pinned API module sources that back the registered kinds, so scope and maturity are read from the modules kure actually builds against rather than from a table maintained by hand. |
|
Package metallb exposes helper functions for constructing MetalLB resources.
|
Package metallb exposes helper functions for constructing MetalLB resources. |
|
Package prometheus exposes the generated constructors and the admissible sugar for Prometheus operator resources: ServiceMonitor, PodMonitor, PrometheusRule and the other monitoring.coreos.com kinds.
|
Package prometheus exposes the generated constructors and the admissible sugar for Prometheus operator resources: ServiceMonitor, PodMonitor, PrometheusRule and the other monitoring.coreos.com kinds. |
|
Package volsync exposes the generated constructors and the admissible sugar for VolSync (volsync.backube/v1alpha1) resources: ReplicationSource and ReplicationDestination.
|
Package volsync exposes the generated constructors and the admissible sugar for VolSync (volsync.backube/v1alpha1) resources: ReplicationSource and ReplicationDestination. |