Go - get server address from kubeconfig file

335 views Asked by At

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)

1

There are 1 answers

2
larsks On BEST ANSWER

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

If you're curious what other fields are available on the rest.Config object, a quick solution is to print out the config variable using the %+v format specifier:

fmt.Printf("%+v\n", config)

For more details, look at the reference documentation.