kubernetes 列出节点时go-client中出现未定义的错误

mwecs4sa  于 2022-11-21  发布在  Kubernetes
关注(0)|答案(1)|浏览(122)

我是golang的新手,我尝试使用client-go列出我的minikube群集中的节点。我遇到了以下问题:
nodeList.Items未定义(类型 * 无效类型没有字段或方法Items)compilerMissingFieldOrMethod
下面是我的代码片段:

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)
    }
}

谁能帮帮我这里出了什么问题?
谢谢你,谢谢你

jmo0nnb3

jmo0nnb31#

看起来客户机集不是从kubeconfig创建的。我建议您按以下方式创建客户机集。我在这里使用了集群外配置来创建客户机集。您也可以使用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)
    }
}

相关问题