How to Use client-go for Kubernetes API Access

Use `client-go` by initializing a `RESTClient` or typed client with a `Config` object derived from either an in-cluster environment or a local kubeconfig file, then call methods like `Get`, `List`, or `Create` on the specific resource interface.

Use client-go by initializing a RESTClient or typed client with a Config object derived from either an in-cluster environment or a local kubeconfig file, then call methods like Get, List, or Create on the specific resource interface. You typically load the config using clientcmd for local development and InClusterConfig for production pods, then wrap the REST client in a typed client (e.g., kubernetes.Interface) for ergonomic access to resources like Pods or Deployments.

For local development using your kubeconfig file, load the config and create a clientset to interact with the API server:

package main

import (
	"context"
	"fmt"
	"os"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
)

func main() {
	home := homedir.HomeDir()
	kubeconfig := fmt.Sprintf("%s/.kube/config", home)

	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	pods, err := clientset.CoreV1().Pods("default").List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("Found %d pods in default namespace\n", len(pods.Items))
}

When running inside a Kubernetes cluster, use InClusterConfig to automatically pick up the service account credentials and API server address without needing a kubeconfig file:

package main

import (
	"context"
	"fmt"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

func main() {
	config, err := rest.InClusterConfig()
	if err != nil {
		panic(err.Error())
	}

	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// Create a simple pod
	pod := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: "test-pod"},
		Spec: corev1.PodSpec{
			Containers: []corev1.Container{{Name: "busybox", Image: "busybox"}},
		},
	}

	_, err = clientset.CoreV1().Pods("default").Create(context.TODO(), pod, metav1.CreateOptions{})
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("Pod created successfully")
}

Remember to handle context cancellation for timeouts and ensure your ServiceAccount has the necessary RBAC permissions to perform the requested actions. The client-go library also provides dynamic clients if you need to interact with CRDs or resources not covered by the standard typed clients.