Documentation
¶
Overview ¶
Package k8s provides Kubernetes client configuration and general-purpose utilities.
This package offers reusable utilities for working with Kubernetes clusters, including REST client configuration, kubeconfig management, DNS label sanitization, and label extraction.
For resource readiness polling, see the [readiness] sub-package.
Key features:
- REST config building from kubeconfig files (BuildRESTConfig, GetRESTConfig)
- Clientset creation (NewClientset)
- Kubeconfig cleanup (CleanupKubeconfig)
- DNS label sanitization (SanitizeToDNSLabel)
- Label value extraction (UniqueLabelValues)
Index ¶
- Variables
- func AddOIDCKubeconfigEntries(cfg *OIDCExecConfig, logWriter io.Writer) error
- func BuildRESTConfig(kubeconfig, context string) (*rest.Config, error)
- func CleanupKubeconfig(kubeconfigPath string, clusterName string, contextName string, userName string, ...) error
- func CleanupOIDCKubeconfigEntries(kubeconfigPath, displayName string, logWriter io.Writer) error
- func DefaultKubeconfigPath() string
- func DiagnoseCluster(ctx context.Context, clientset kubernetes.Interface) (string, error)
- func DiagnosePodFailures(ctx context.Context, clientset kubernetes.Interface, namespaces []string) string
- func EnsurePrivilegedNamespace(ctx context.Context, clientset kubernetes.Interface, name string) error
- func GetRESTConfig() (*rest.Config, error)
- func MergeSecretData(secret *corev1.Secret, desiredData map[string][]byte) bool
- func NewClientset(kubeconfig, context string) (*kubernetes.Clientset, error)
- func NewDynamicClient(kubeconfig, context string) (dynamic.Interface, error)
- func RenameKubeconfigContext(kubeconfigData []byte, desiredContext string) ([]byte, error)
- func SanitizeToDNSLabel(value string) string
- func SecretDataContains(existing, desiredData map[string][]byte) bool
- func UniqueLabelValues[T any](items []T, key string, getLabels func(T) map[string]string) []string
- type OIDCExecConfig
Constants ¶
This section is empty.
Variables ¶
var ErrKubeconfigContextCollision = errors.New("kubeconfig context name collision")
ErrKubeconfigContextCollision is returned when the desired context name already exists as a different context entry in the kubeconfig.
var ErrKubeconfigContextNotFound = errors.New("kubeconfig context not found")
ErrKubeconfigContextNotFound is returned when the specified context name does not exist in the kubeconfig.
var ErrKubeconfigNoCurrentContext = errors.New("kubeconfig has no current context")
ErrKubeconfigNoCurrentContext is returned when a kubeconfig has no current context and multiple context entries, making it ambiguous which context to rename.
var ErrKubeconfigPathEmpty = errors.New("kubeconfig path is empty")
ErrKubeconfigPathEmpty is returned when kubeconfig path is empty.
Functions ¶
func AddOIDCKubeconfigEntries ¶ added in v7.10.0
func AddOIDCKubeconfigEntries(cfg *OIDCExecConfig, logWriter io.Writer) error
AddOIDCKubeconfigEntries adds an exec-based OIDC user and context to the kubeconfig. The user is named "oidc-<clusterName>" and the context is named "oidc@<clusterName>". The admin context remains the current context.
func BuildRESTConfig ¶
BuildRESTConfig builds a Kubernetes REST config from kubeconfig path and optional context.
The kubeconfig parameter must be a non-empty path to a valid kubeconfig file. The context parameter is optional and specifies which context to use from the kubeconfig. If context is empty, the default context from the kubeconfig is used.
Returns ErrKubeconfigPathEmpty if kubeconfig path is empty. Returns an error if the kubeconfig cannot be loaded or parsed.
func CleanupKubeconfig ¶
func CleanupKubeconfig( kubeconfigPath string, clusterName string, contextName string, userName string, logWriter io.Writer, ) error
CleanupKubeconfig removes the cluster, context, and user entries for a cluster from the kubeconfig file. This only removes entries matching the provided names, leaving other cluster configurations intact.
Parameters:
- kubeconfigPath: absolute path to the kubeconfig file
- clusterName: the cluster entry name to remove
- contextName: the context entry name to remove
- userName: the user/authinfo entry name to remove
- logWriter: writer for log output (can be io.Discard)
func CleanupOIDCKubeconfigEntries ¶ added in v7.10.0
CleanupOIDCKubeconfigEntries removes the OIDC user and context entries for a cluster. The displayName is the user-friendly cluster name (e.g. "local") used in OIDC naming.
func DefaultKubeconfigPath ¶
func DefaultKubeconfigPath() string
DefaultKubeconfigPath returns the default kubeconfig path for the current user. The path is constructed as ~/.kube/config using the user's home directory.
func DiagnoseCluster ¶ added in v7.4.1
DiagnoseCluster produces a combined human-readable diagnostic report for a running Kubernetes cluster. It enumerates every namespace, surfaces any failing pods via DiagnosePodFailures, and reports any nodes that are not Ready. When everything appears healthy, the returned string is empty.
The diagnostic is intentionally distribution-agnostic — it only relies on the Kubernetes API and therefore works for Vanilla, K3s, Talos, and VCluster alike. It is consumed by the `ksail cluster diagnose` command and surfaced to the Copilot chat/MCP tooling via the auto-generated `cluster_read` tool so AI assistants can reason over the output.
func DiagnosePodFailures ¶
func DiagnosePodFailures( ctx context.Context, clientset kubernetes.Interface, namespaces []string, ) string
DiagnosePodFailures checks pods in the given namespaces and returns a human-readable summary of any pods that are not running successfully. If all pods are healthy or no pods exist, it returns an empty string.
func EnsurePrivilegedNamespace ¶
func EnsurePrivilegedNamespace( ctx context.Context, clientset kubernetes.Interface, name string, ) error
EnsurePrivilegedNamespace creates the given namespace with PodSecurity Standard "privileged" labels, or updates an existing namespace to add them.
func GetRESTConfig ¶
GetRESTConfig loads the kubeconfig using default loading rules and returns a REST config. This is a convenience function that uses the standard client-go loading rules (KUBECONFIG env var, default kubeconfig path) without requiring explicit paths.
func MergeSecretData ¶ added in v7.8.0
MergeSecretData merges desiredData into secret.Data in place, setting StringData to nil to avoid conflicts. It returns false (no update needed) when every key in desiredData already matches the existing value.
func NewClientset ¶
func NewClientset(kubeconfig, context string) (*kubernetes.Clientset, error)
NewClientset creates a Kubernetes clientset from kubeconfig path and context. This is a convenience function that combines BuildRESTConfig and client creation.
func NewDynamicClient ¶
NewDynamicClient creates a Kubernetes dynamic client from kubeconfig path and context. This is a convenience function that combines BuildRESTConfig and dynamic client creation. Use this when working with unstructured resources or custom resource types.
func RenameKubeconfigContext ¶
RenameKubeconfigContext renames the current context (and its associated cluster and user entries) in raw kubeconfig bytes to desiredContext.
If desiredContext is empty, the kubeconfig is returned unchanged. If desiredContext already matches the current context, the kubeconfig is returned unchanged. If there is no current context but the kubeconfig can be resolved without ambiguity, the kubeconfig is updated to set CurrentContext to desiredContext. Returns an error when the desired context name collides with an existing different context entry, or when CurrentContext is empty and no single context entry can be unambiguously selected.
func SanitizeToDNSLabel ¶
SanitizeToDNSLabel converts an arbitrary string to a lowercase alphanumeric string with hyphens as the only separator. Consecutive hyphens are collapsed and leading/trailing hyphens are trimmed.
This is the shared sanitization kernel used by OCI repository segment normalisation and DNS-1123 repo name construction.
func SecretDataContains ¶ added in v7.8.0
SecretDataContains returns true when every key in desiredData exists in existing with an equal value.
Types ¶
type OIDCExecConfig ¶ added in v7.10.0
type OIDCExecConfig struct {
// KubeconfigPath is the absolute path to the kubeconfig file.
KubeconfigPath string
// ClusterEntryName is the kubeconfig cluster entry name (e.g. "kind-local", "k3d-local").
// This is used as the context.cluster reference.
ClusterEntryName string
// DisplayName is the user-friendly cluster name (e.g. "local") used for
// naming the OIDC user ("oidc-local") and context ("oidc@local").
DisplayName string
// IssuerURL is the OIDC provider issuer URL.
IssuerURL string
// ClientID is the OIDC client ID.
ClientID string
// ExtraScopes are additional OIDC scopes to request.
ExtraScopes []string
// CAFile is an optional path to the OIDC provider's CA certificate.
CAFile string
}
OIDCExecConfig holds the parameters for configuring an OIDC exec credential plugin in kubeconfig.