使用Kubernetes Client-Go获取集群ID

时间:2019-02-14 09:52:21

标签: kubernetes client-go

我正在为Kubernetes使用client-go并试图获取当前集群的ID,即类似于kubectl cluster-info的输出。 我found的函数叫getCluster

func (config *DirectClientConfig) ClientConfig() (*restclient.Config, error) {
    // check that getAuthInfo, getContext, and getCluster do not return an error.
    // Do this before checking if the current config is usable in the event that an
    // AuthInfo, Context, or Cluster config with user-defined names are not found.
    // This provides a user with the immediate cause for error if one is found
    configAuthInfo, err := config.getAuthInfo()
    if err != nil {
        return nil, err
    }

    _, err = config.getContext()
    if err != nil {
        return nil, err
    }

    configClusterInfo, err := config.getCluster()
    if err != nil {
        return nil, err
    }

    ...
}

当我在代码中编写以下内容

config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
clusterInfo, err := config.getCluster()

我收到错误config.getCluster undefined (type *rest.Config has no field or method getCluster)

如何使用此功能?还有其他方法可以获取群集ID吗?

2 个答案:

答案 0 :(得分:0)

在您提供的链接中,您似乎需要使用clusterInfo, err := config.getCluster()而不是configAuthInfo.getCluster()

答案 1 :(得分:0)

$ kubectl cluster-info

1. Kubernetes master is running at https://10.156.0.3:6443
2. KubeDNS is running at https://10.156.0.3:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

如果运行kubectl cluster-info -v8,则会看到以下内容:

第一行基本上是从您的~/.kube/config文件中提取的,kubectl只是通过简单的GET请求来检查其是否有效,以寻找应该在集群:

I0222 11:21:18.015482   18150 round_trippers.go:416] GET https://10.156.0.3:6443/api/v1/namespaces/kube-system/services?labelSelector=kubernetes.io%2Fcluster-service%3Dtrue

您可以通过启动kubectl proxy然后在其他控制台中获得此命令的结果:

curl http://127.0.0.1:8001/api/v1/namespaces/kube-system/services?labelSelector=kubernetes.io%2Fcluster-service%3Dtrue 

正如您在响应中看到的那样,那里没有包含主URL的行。

因此,要获取在kubectl cluster-info输出的第一行中指定的值,您只需要读取Kubernetes配置文件的正确部分,因为您可以在其中放置several cluster configuration

要读取和反序列化Kubernetes配置文件,loader.go中有一个功能:

// LoadFromFile takes a filename and deserializes the contents into Config object
func LoadFromFile(filename string) (*clientcmdapi.Config, error)
 

config.go中的另一个功能:

// getConfigFromFile tries to read a kubeconfig file and if it can't, returns an error.  One exception, missing files result in empty configs, not an error.
func getConfigFromFile(filename string) (*clientcmdapi.Config, error)