Kubernetes API - Programmatically Interacting with the API

Programmatically Interacting with the API

Create a Golang program to list pods in the cluster
cd $HOME
mkdir client-go-example
cd client-go-example
Create a package
go mod init client-go-example
Create main.go to access the cluster and list the pods.
cat <<EOF > main.go
package main

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

func main() {
   // uses the current context in kubeconfig
   // path-to-kubeconfig -- for example, /root/.kube/config
   config, _ := clientcmd.BuildConfigFromFlags("", "<path-to-kubeconfig>")
   // creates the clientset
   clientset, _ := kubernetes.NewForConfig(config)
   // access the API to list pods
   pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
   fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
}
EOF
Edit main.go with replacing <path-to-kubeconfig> with /home/ec2-user/.kube/config
config, _ := clientcmd.BuildConfigFromFlags("", "/home/ec2-user/.kube/config")
Before you can run the program, you need to download external modules
go mod tidy
Run the program
go run main.go

Observe the output. How many pods are listed in the cluster? A lot. This is because it is listing all the pods in the cluster.

Now we’re going switch gear and list pods in the myns namespace only.

Create a new namespace
oc new-project myns
Create a pod using the nginx image
kubectl run nginx --image=nginx --restart=Never
Now edit the main.go file and change
pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})

to

pods, _ := clientset.CoreV1().Pods("myns").List(context.TODO(), v1.ListOptions{})
Run the program
go run main.go

Observe the output. How many pods are listed now? Only one. This is because it’s listing pods in the myns namespace that we just created.