Suppose there is a service with name "SVC", running in namespace NS in kubernetes cluster. I need to extract its IP (i.e clusterIP)
I could write some code (below), which works, but I think this approach should not be taken. As this code will be called frequently, loading config every time is a waste. How should I better do it:
namespace := "NS"
serviceName := "SVC"
clusterIP := ""
kubeconfig := filepath.Join(
os.Getenv("HOME"), ".kube", "config",
)
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
fmt.Println("BuildConfigFromFlags Failed")
return string(""), err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println("NewForConfig Failed")
return string(""), err
}
svcList, err := clientset.CoreV1().Services(namespace).List(metav1.ListOptions{
FieldSelector: "metadata.name=" + serviceName,
})
//fmt.Printf("kubecofig: %s\n",kubeconfig)
//fmt.Printf("config: %#v", config)
//fmt.Printf("nameSpaceList: %#v", svcList)
for _, svc := range svcList.Items {
clusterIP = svc.Spec.ClusterIP
break
}
fmt.Printf("Service IP: %s", clusterIP)
Is there a way I can write concise code like this and get my desired result. If there is a way to use "&corev1.service" , can anybody please tell me how?