Go: how to use the Kubernetes API

Go: how to use the Kubernetes API

In this article, we will explore how to use Kubernetes APIs in the Go programming language to develop custom applications that interact directly with the Kubernetes cluster.

Kubernetes is an open-source system for automating the deployment, scaling, and management of containerized applications. A fundamental aspect of Kubernetes is its API, which allows developers to interact with the cluster to create, manage, and monitor resources. In this article, we will explore how to use Kubernetes APIs in the Go programming language to develop custom applications that interact directly with the Kubernetes cluster.

Installing Dependencies

To interact with Kubernetes APIs in Go, you need to install the official client package. You can do this using the go get command:


go get -u k8s.io/client-go@v0.0.0-20220121182751-531c2a95aa75

Configuring the Kubernetes Client

To interact with the Kubernetes cluster, you need to configure the client. This can be done using the cluster configuration file (usually located in ~/.kube/config). The client-go provides configuration management features:


package main

import (
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
	if err != nil {
		panic(err.Error())
	}

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

	// Now the clientset is configured to interact with the Kubernetes cluster.
	// We will continue to use the clientset in the following sections.
}

Using Kubernetes APIs

With the configured clientset, we can use Kubernetes APIs to perform various operations. For example, to get the list of nodes in the cluster:


package main

import (
	"fmt"
	"context"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
	if err != nil {
		panic(err.Error())
	}

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

	// Get the list of nodes in the cluster
	nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		panic(err.Error())
	}

	// Print the names of the nodes
	for _, node := range nodes.Items {
		fmt.Printf("Node: %s\n", node.Name)
	}
}

Creating Custom Resources

You can use Kubernetes APIs to create, update, or delete custom resources. For example, to create a new Deployment resource:


package main

import (
	"context"
	"fmt"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	corev1 "k8s.io/api/core/v1"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
	if err != nil {
		panic(err.Error())
	}

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

	// Define the new Deployment object
	deployment := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: "example-deployment",
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: int32Ptr(3),
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app": "example",
				},
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"app": "example",
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{
						{
							Name:  "example-container",
							Image: "nginx:latest",
						},
					},
				},
			},
		},
	}

	// Create the new Deployment object
	result, err := clientset.AppsV1().Deployments("default").Create(context.TODO(), deployment, metav1.CreateOptions{})
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("Deployment created: %s\n", result.GetObjectMeta().GetName())
}

func int32Ptr(i int32) *int32 { return &i }

Conclusion

In this article, we explored how to use Kubernetes APIs in Go to interact with the Kubernetes cluster. From configuring the client to retrieving existing resources and creating custom resources, developers can harness the power of Kubernetes APIs to automate and customize cluster operations. We hope this tutorial provides a solid foundation for developing custom applications on Kubernetes using the Go programming language.