如何使用kubernetes go-client获取节点的私有IP?

时间:2017-06-02 08:23:38

标签: kubernetes kubernetes-go-client

在我的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?

非常感谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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)
}