Go - 从 kubeconfig 文件中获取服务器地址

基本上,我的 kubeconfig 文件有:


apiVersion: v1

clusters:

 - cluster:

      server: <OAM ip address> this is what I want

(...)

我想获取服务器地址。以前搜索,我找到了这个解决方案:


config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)

if err != nil {

    panic(err.Error())

}

// creates the clientset

clientset, err := kubernetes.NewForConfig(config)

if err != nil {

    panic(err.Error())

}


nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})

if err != nil {

    panic(err)

}

nodeip := []corev1.NodeAddress{}

for i := 0; i < len(nodes.Items); i++ {

    nodeip = nodes.Items[i].Status.Addresses

    fmt.Println(nodeip[0].Address)

}

fmt.Println(nodes.Items[0].Status.Addresses)

但它给了我内部 IP,而不是 OAM 服务器 IP(在 Kubernetes 配置文件中)


慕神8447489
浏览 105回答 1
1回答

绝地无双

如果您想要文件中的服务器地址,只需从您的变量kubeconfig中读取它:configpackage mainimport (&nbsp; &nbsp; "flag"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "path/filepath"&nbsp; &nbsp; "k8s.io/client-go/kubernetes"&nbsp; &nbsp; "k8s.io/client-go/tools/clientcmd"&nbsp; &nbsp; "k8s.io/client-go/util/homedir")func main() {&nbsp; &nbsp; var kubeconfig *string&nbsp; &nbsp; if home := homedir.HomeDir(); home != "" {&nbsp; &nbsp; &nbsp; &nbsp; kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")&nbsp; &nbsp; }&nbsp; &nbsp; flag.Parse()&nbsp; &nbsp; config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("server: %s\n", config.Host)}如果您好奇对象上还有哪些其他字段可用,一个快速的解决方案是使用格式说明符rest.Config打印出变量:config%+vfmt.Printf("%+v\n", config)有关详细信息,请查看参考文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go