Delete Kubernetes Pods with Golang and a Dash of Fun!

Mehran
4 min readMar 21, 2023
Generated using Lexica

Introduction:

Hey, Kubernetes enthusiasts! Have you ever wondered how to delete pods using Golang? Today, we’ll dive into the world of Kubernetes and Golang and create a fun little program that does just that. So, buckle up, and let’s get started!

  1. Setting the Stage:

Before we begin, make sure you have Go installed on your system. If not, head over to the official Golang website and get it set up. Also, we’ll be using the Kubernetes client-go library to interact with the cluster, so make sure to install it with the following command:

go get k8s.io/client-go@v0.22.4

2. The Power of Golang:

Golang, or simply “Go,” is a statically-typed, compiled programming language designed for simplicity and efficiency. It’s perfect for working with distributed systems like Kubernetes. And now, let’s create a program that leverages the power of Go to connect to a Kubernetes cluster and delete pods!

3. The Main Attraction: Code!

Create a new file called main.go and paste the following code. Don't worry! We'll break it down and explain everything so it's crystal clear and fun.

package main

import (
"context"
"flag"
"fmt"
"os"

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

func main() {
kubeconfig := flag.String("kubeconfig", "", "path to the kubeconfig file (default: use in-cluster configuration)")
namespace := flag.String("namespace", "default", "the namespace of the pods to delete")
podName := flag.String("pod", "", "the name of the pod to delete (required)")

flag.Parse()

if *podName == "" {
fmt.Fprintln(os.Stderr, "Please provide the pod name.")
flag.Usage()
os.Exit(1)
}

var config *rest.Config
var err error

if *kubeconfig == "" {
config, err = rest.InClusterConfig()
} else {
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
}

if err != nil {
fmt.Fprintf(os.Stderr, "Error creating Kubernetes client configuration: %v\n", err)
os.Exit(1)
}

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating Kubernetes client: %v\n", err)
os.Exit(1)
}

ctx := context.Background()

err = deletePod(ctx, clientset, *namespace, *podName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error deleting pod: %v\n", err)
os.Exit(1)
}

fmt.Printf("Pod %s in namespace %s deleted successfully\n", *podName, *namespace)
}

func deletePod(ctx context.Context, clientset *kubernetes.Clientset, namespace, podName string) error {
deletePolicy := metav1.DeletePropagationForeground
return clientset.CoreV1().Pods(namespace).Delete(ctx, podName, metav1.DeleteOptions{
PropagationPolicy: &deletePolicy,
})
}

4. Code Breakdown (Fun-Style!):

  • First, we import all the necessary packages. We need the context, flag, fmt, and os packages from the standard library and a few boxes from the client-go library to interact with Kubernetes.
  • In the main function, we define three command-line flags: kubeconfig, namespace, and pod. These flags allow users to pass the kubeconfig file path, the desired namespace, and the pod name they want to delete.
  • We use flag.Parse() to parse the command-line arguments, check if the required pod flag has been provided. If not, we print a helpful message and exit the Program.
  • Next, we create a Kubernetes client configuration (rest.Config). If the kubeconfig the flag is not provided; we assume we're running inside a Kubernetes cluster and use the in-cluster design. Otherwise, we use the provided kubeconfig file.
  • With the configuration in hand, we create a new Kubernetes client (kubernetes.Clientset) to interact with the cluster.
  • We then create a context using context.Background(). Contexts are used to manage the lifecycle of API calls, allowing you to cancel requests or set timeouts.
  • Finally, we call the deletePod the function uses context, clientset, namespace, and pod name as arguments. If everything goes well, we print a success message. If there's an error, we print it and exit.
  • In the deletePod function, we define a DeletePropagationForeground Policy means the pod will be deleted only when all its dependents are deleted. Then, we call the Delete method on the clientset.CoreV1().Pods(namespace) object, passing the context, pod name, and delete options.

5. Build and Run the Fun Program:

To build the Program, open a terminal, navigate to the folder containing main.go, and run:

go build -o delete-pod main.go

This will generate an executable called. delete-pod. Now, you can run the Program with the following:

./delete-pod --kubeconfig ~/.kube/config --namespace my-namespace --pod my-pod

Make sure to replace my-namespace and my-pod with the actual namespace and pod name you want to delete. If you're running the Program within a cluster, you can skip the --kubeconfig flag.

Conclusion:

And there you have it! You’ve created a fun and easy-to-use Golang program to connect to a Kubernetes cluster and delete pods. Happy coding! You can impress your friends and colleagues with your newfound Kubernetes and Golang superpowers.

--

--

Mehran

Tech Team Lead | Cloud, Video & Microservices Expert | Insights on streaming innovations & programming. #ContinuousLearning