【问题标题】:how to get a node's private IP using kubernetes go-client?如何使用 kubernetes go-client 获取节点的私有 IP?
【发布时间】:2017-11-03 13:59:12
【问题描述】:

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

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?

非常感谢。

【问题讨论】:

    标签: kubernetes kubernetes-go-client


    【解决方案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

    【讨论】:

      【解决方案2】:
      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)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-20
        • 2022-01-23
        • 2018-11-27
        • 2020-07-01
        • 1970-01-01
        • 2020-11-22
        • 2019-12-09
        • 2021-08-10
        相关资源
        最近更新 更多