How to extract the active HPA in Kubernetes using go-lang

9/9/2020

I am using a kube config file to fetch the pod CPU and MEM data using go-lang. I am stuck to fetch the HPA details, i.e I am trying to write the equivalent of "kubectl get hpa", so I can know I have applied hpa to known services or not.

Any help on this is highly appreciated.

I have tried the below so far.

kubeClient "k8s.io/client-go/kubernetes/typed/autoscaling/v1"
hpaWatch, err := kubeClient.AutoscalingV1().HorizontalPodAutoscalers("default").Watch(metav1.ListOptions{})

But this is not working.

-- abinash
go
kubernetes
kubernetes-hpa

1 Answer

9/9/2020

Here is the line you should have used:

hpas, err := clientset.AutoscalingV1().HorizontalPodAutoscalers("default").List(context.TODO(), metav1.ListOptions{})

and the following is a complete and working example for listing HPAs. You should be able just copy-paste it and run it.

It was tested with client-go@0.19.0.

package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"time"

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

func main() {
	var kubeconfig *string
	if home := homeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	for {
		hpas, err := clientset.AutoscalingV1().HorizontalPodAutoscalers("default").List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			panic(err.Error())
		}

		for _, hpa := range hpas.Items {
			fmt.Printf("%q\n", hpa.GetName())
		}

		time.Sleep(10 * time.Second)
	}
}

func homeDir() string {
	if h := os.Getenv("HOME"); h != "" {
		return h
	}
	return os.Getenv("USERPROFILE") // windows
}
-- Matt
Source: StackOverflow