List all namespaces in k8s in Go

4.7k views Asked by At

Can anyone tell me how to list all namespaces in k8s using Go? I have been referencing this link but couldn't find anything that can list all namespaces.

Link: https://pkg.go.dev/github.com/gruntwork-io/terratest/modules/k8s

I don't see any ListNamespaces functions for the k8s package in Go.

2

There are 2 answers

0
gohm'c On

Try kubernetes/client-go, you can do like clientset.CoreV1().Namespaces("").List(context.TODO(), metav1.ListOptions{}). Your clientset maybe instantiate within the cluster or outside.

0
Sam On

To list namespaces you can use something like this:

func ListNameSpaces(coreClient kubernetes.Interface) {

    nsList, err := coreClient.CoreV1().
        Namespaces().
        List(context.Background(), metav1.ListOptions{})
    //checkErr(err)
    fmt.Println(err)

    for _, n := range nsList.Items {
        fmt.Println(n.Name)
    }
}