Talk To K8s Cluster using Go

Talk To K8s Cluster using Go

Introduction

In the dynamic world of cloud-native development, Kubernetes is the go-to platform for managing containerized applications. While kubectl is the standard tool for interacting with Kubernetes clusters, there are scenarios where you may want to automate these interactions within your application code. This is where the Kubernetes Go client library becomes invaluable. This blog post will guide you through the basics of programmatically interacting with Kubernetes using Go.

Prerequisites

Before diving into the code, ensure you have the following:

  • A running Kubernetes cluster in local .

  • Go installed on your machine.

  • The client-go library installed (go get k8s.io/client-go).

  • Access to your Kubernetes configuration file (~/.kube/config).

Code Walkthrough

Let's dive into the Go code that lists the Pods and Deployments in the "default" namespace of your Kubernetes cluster.

1. Importing Required Packages

import (
    "context"
    "flag"
    "fmt"

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

Here, we import the necessary packages for Kubernetes API interactions and handling context and configuration.

2. Setting Up the Context and Configuration

ctx := context.Background()
kubeconfig := flag.String("kubeconfig", "/home/anish/.kube/config", "other path")
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
    fmt.Printf("Error in building kubeconfig file %s", error.Error(err))
}
  • Context: Used to control the lifetime of requests to Kubernetes.

  • Kubeconfig: Specifies the path to the Kubernetes config file.

  • BuildConfigFromFlags: This method loads the Kubernetes configuration from the specified file.

3. Creating the Kubernetes Client

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    fmt.Printf("Error in creating the client set %s ", err.Error())
}

The clientset is the main interface to interact with Kubernetes. It is created using the loaded configuration.

4. Listing Pods in the Default Namespace

pods, err := clientset.CoreV1().Pods("default").List(ctx, v1.ListOptions{})
if err != nil {
    fmt.Printf("Error in Listing the pod %s ", error.Error(err))
}
fmt.Println("The pods are:")
for _, pod := range pods.Items {
    fmt.Printf("%s\n", pod.Name)
}

This section lists all the pods in the "default" namespace and prints their names.

5. Listing Deployments in the Default Namespace

deployments, err := clientset.AppsV1().Deployments("default").List(ctx, v1.ListOptions{})
if err != nil {
    fmt.Printf("Error in Listing the deployment %s\n ", error.Error(err))
}
fmt.Println("The deployments are:")
for _, d := range deployments.Items {
    fmt.Printf("%s\n", d.Name)
}

Similarly, this part lists all the deployments in the "default" namespace and prints their names.

Running the Code

Compile and run the Go program using:

go run main.go

Ensure your Kubernetes cluster is running, and you have the correct context configured in your ~/.kube/config file.

At the first you will not see any pod and deployment because you have not created yet.

Deploying an Application

create a simple deployment in the "default" namespace:

kubectl create deployment nginx --image=nginx --replicas 3

This command creates a deployment named "nginx" using the official Nginx image.

Expected Output

Again, run the code then you will see pod and deployment in the output.

In my case the output look like

The pods are:
nginx-bf5d5cf98-4smn6
nginx-bf5d5cf98-5ddcm
nginx-bf5d5cf98-szmbb
The deployment are:
nginx

Conclusion

This simple Go program demonstrates how to programmatically interact with a Kubernetes cluster using the Kubernetes Go client library. Whether listing pods, deployments, or other resources, the client-go library provides a powerful and flexible way to automate tasks in your Kubernetes environment.

What's next

Right now we are talking to our cluster from outside. In next blog i will migrate this application inside the cluster and try to get same output.

Stay tuned :)