How do I interact with the Kubernetes API from Go?

Interacting with the Kubernetes API from Go allows developers to automate and manage Kubernetes resources efficiently. This guide covers the essential steps to communicate effectively with the Kubernetes API.
Kubernetes API, Go client, Go programming, Kubernetes management, API interaction
package main import ( "context" "fmt" "log" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) func main() { // Load kubeconfig file kubeconfig := "/path/to/your/kubeconfig" // Update this path config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { log.Fatalf("Error building kubeconfig: %s", err.Error()) } // Create a clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { log.Fatalf("Error creating Kubernetes clientset: %s", err.Error()) } // Get a list of pods in the default namespace pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) if err != nil { log.Fatalf("Error fetching pod list: %s", err.Error()) } fmt.Println("Pods in the cluster:") for _, pod := range pods.Items { fmt.Printf("- %s\n", pod.Name) } }

Kubernetes API Go client Go programming Kubernetes management API interaction