0

在我的 kubernetes 集群中,所有节点都有一个公共 IP 和一个私有 IP。我正在使用 kubernetes go-client 并希望获取节点的私有 IP,如下面的代码片段:

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

但是,NodeInternalIP 和 NodeExternalIP 都返回公共 IP。

有没有办法获取节点的私有IP?

非常感谢。

4

2 回答 2

1

这应该为您提供节点的内部私有 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

于 2017-06-09T06:49:25.380 回答
0
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)
}
于 2019-03-16T05:15:43.147 回答