Reputation: 164
In my kubernetes cluster, all nodes have both a public IP and a private IP. I am using kubernetes go-client and want to get node's private IP like below code snippet:
for _, addr := range n.Status.Addresses {
if addr.Type == kube_api.NodeInternalIP && addr.Address != "" {
fmt.Println("internal IP")
nodeIP = addr.Address
fmt.Println(nodeIP)
}
if addr.Type == kube_api.NodeExternalIP && addr.Address != "" {
fmt.Println("external IP")
nodeIP = addr.Address
fmt.Println(nodeIP)
}
if addr.Type == kube_api.NodeLegacyHostIP && addr.Address != "" {
fmt.Println("lgeacyhost IP")
nodeIP = addr.Address
fmt.Println(nodeIP)
}
}
However, the NodeInternalIP and NodeExternalIP all returns the public IP.
Is there a way to get the private IP of a node?
Thanks a lot.
Upvotes: 0
Views: 3557
Reputation: 781
package main
import (
"flag"
"fmt"
"path/filepath"
_ "net/http/pprof"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1 "k8s.io/api/core/v1"
"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()
// uses the current context in kubeconfig
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)
}
Upvotes: 0
Reputation: 811
This should provide you the node's Internal private IP
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
172.20.38.232 172.20.48.54 172.20.53.226 172.20.55.210
Upvotes: 0