Home > Net >  Go - get server address from kubeconfig file
Go - get server address from kubeconfig file

Time:10-27

Basically, my kubeconfig file has:

apiVersion: v1
clusters:
 - cluster:
      server: <OAM ip address> this is what I want
(...)

I want to get the server address. Previously searching , I've found this solution:

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)

But it gives me the Internal IP, not the OAM server IP (which is inside the Kubernetes config file)

CodePudding user response:

If you want the server address from the kubeconfig file, just read it from your config variable:

package main

import (
    "flag"
    "fmt"
    "path/filepath"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"
)

func main() {
    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)
    }

    fmt.Printf("server: %s\n", config.Host)
}
  • Related