Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save smreed/25cc3362d2a391a1e8d4ed3ef41a6bce to your computer and use it in GitHub Desktop.
Save smreed/25cc3362d2a391a1e8d4ed3ef41a6bce to your computer and use it in GitHub Desktop.
Go code that will connect to a production Kubernetes API if run in cluster, or to the whichever cluster you have `kubectl` configured to hit.

I find myself writing this a lot for code that I want to work in production, but also in a development environment.

This has been tested on k8s 1.2.2.

You must have the correct version of github.com/imdario/mergo vendored. Look at k8s.io/kubernetes/Godeps/Godeps.json to see which commit is used by Kubernetes.

TODO: add the vendor/manifest file that gb could use to restore vendored dependencies, since minimizing that just to get the code below to work is a monumental effort as well.

package main
import (
"fmt"
"log"
"k8s.io/kubernetes/pkg/client/restclient"
"k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)
func main() {
cfg, err := findK8sConfig()
if err != nil {
log.Fatal(err)
}
client, err := unversioned.New(cfg)
fmt.Printf("client=%v, err=%v\n", client, err)
}
func findK8sConfig() (cfg *restclient.Config, err error) {
// Try in-cluster first
if cfg, err = restclient.InClusterConfig(); err == nil {
return cfg, nil
}
// Fall-back to local ~/.kube/config
opts, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
if err != nil {
return nil, err
}
overrides := &clientcmd.ConfigOverrides{}
return clientcmd.NewDefaultClientConfig(*opts, overrides).ClientConfig()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment