Reputation: 3873
I am new to golang
and I am trying to list the nodes in my minikube
cluster with the client-go
. And I encounter the following issue:
nodeList.Items undefined (type *invalid type has no field or method Items)compilerMissingFieldOrMethod
And here's my code snippet for this:
package main
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
rules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})
config, err := kubeconfig.ClientConfig()
if err != nil {
panic(err)
}
clientset := kubernetes.NewForConfigOrDie(config)
nodeList, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}
for _, node := range nodeList.Items {
fmt.Printf("%s\n", node.Name)
}
}
Can someone help me what is the problem here?
Thank you!
Upvotes: 2
Views: 998
Reputation: 446
It looks like the clientset is not created from your kubeconfig. I would suggest you to create the clientset in the following way. I have used out of cluster config here to create the clientset. You can also create it using InclusterConfig.
package main
import (
"context"
"flag"
"fmt"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/homedir"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// parse the .kubeconfig file
var kubeconfig *string
if home := homedir.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()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
nodeList, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
panic(err)
}
for _, node := range nodeList.Items {
fmt.Printf("%s\n", node.Name)
}
}
Upvotes: 1