在kubernetes client-go中使用kubectl上下文

时间:2018-05-20 13:56:46

标签: go kubernetes

如何使用普通上下文配置kubernetes client-go?

    package kube

    import (
        "fmt"

        "k8s.io/client-go/kubernetes"
        "k8s.io/client-go/rest"
        "k8s.io/client-go/tools/clientcmd"
    )

    // GetKubeClient creates a Kubernetes config and client for a given kubeconfig context.
    func GetKubeClient(context string) (*rest.Config, kubernetes.Interface, error) {
        config, err := configForContext(context)
        if err != nil {
            return nil, nil, err
        }
        client, err := kubernetes.NewForConfig(config)
        if err != nil {
            return nil, nil, fmt.Errorf("could not get Kubernetes client: %s", err)
        }
        return config, client, nil
    }

    // configForContext creates a Kubernetes REST client configuration for a given kubeconfig context.
    func configForContext(context string) (*rest.Config, error) {
        config, err := getConfig(context).ClientConfig()
        if err != nil {
            return nil, fmt.Errorf("could not get Kubernetes config for context %q: %s", context, err)
        }
        return config, nil
    }

    // getConfig returns a Kubernetes client config for a given context.
    func getConfig(context string) clientcmd.ClientConfig {
        rules := clientcmd.NewDefaultClientConfigLoadingRules()
        rules.DefaultClientConfig = &clientcmd.DefaultClientConfig

        overrides := &clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults}

        if context != "" {
            overrides.CurrentContext = context
        }
        return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)
    }

如果我尝试使用此代码(从helm获取),则api服务器设置不正确,客户端想要连接到默认主机localhost:8080

1 个答案:

答案 0 :(得分:1)

发现问题。 github.com/imdario/mergo的实现在较新版本中发生了更改,并打破了生成客户端配置的实际行为。因此,只需使用官方kubernetes cient-go存储库中的修订版6633656539c1639d9d78127b7d47c622b5d7b6dc

https://github.com/kubernetes/client-go/issues/415