<p>How can I use a normal context to configure the kubernetes client-go?</p>

<pre><code>    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 = &amp;clientcmd.DefaultClientConfig

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

        if context != "" {
            overrides.CurrentContext = context
        }
        return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)
    }
</code></pre>

<p>If I try this code (got it from helm), the api server is not correctly set and the client wants to connect to the default host <code>localhost:8080</code>.</p>

Ben Keil
<p>Currently the example recommends doing something like this:</p>
<pre><code>kconf, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)
if err != nil {
    return nil, err
}
</code></pre>
<p>However that won't allow you to specify the context you want to use. If you look at the source code you'll see that BuildConfigFromFlags is a thin wrapper around NewNonInteractiveDeferredLoadingClientConfig.</p>
<p>If you use NewNonInteractiveDeferredLoadingClientConfig instead you can specify the context like this:</p>
<pre><code>configLoadingRules := &amp;clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
configOverrides := &amp;clientcmd.ConfigOverrides{CurrentContext: &quot;dev-cluster&quot;}

kconf, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(configLoadingRules, configOverrides).ClientConfig()
if err != nil {
    return nil, err
}
</code></pre>
