How do I use contexts with Kubernetes clients?

Using contexts with Kubernetes clients in Go is crucial for managing timeouts and cancellation when making API calls. Contexts allow you to control the lifecycle of operations, enabling your applications to handle network delays, respond to shutdown signals, and clean up resources efficiently.

package main import ( "context" "fmt" "time" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) func main() { // Load kubeconfig config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig") if err != nil { panic(err.Error()) } // Create a new clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // Create a context with a timeout ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Ensure resources are cleaned up // Use context with Kubernetes client pods, err := clientset.CoreV1().Pods("default").List(ctx, metav1.ListOptions{}) if err != nil { fmt.Printf("Error listing pods: %v\n", err) return } fmt.Printf("Found %d pods in the 'default' namespace\n", len(pods.Items)) }

Go Kubernetes context API client-go cancellation timeout resource management