Skip to content

Instantly share code, notes, and snippets.

@int128
Created March 20, 2018 07:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int128/a01b044009d407629fbde6985258d74f to your computer and use it in GitHub Desktop.
Save int128/a01b044009d407629fbde6985258d74f to your computer and use it in GitHub Desktop.
Read and write Kubernetes client config (~/.kube/config) in Go
package main
import (
"log"
"os"
"github.com/mitchellh/go-homedir"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeConfigPath, err := findKubeConfig()
if err != nil {
log.Fatal(err)
}
kubeConfig, err := clientcmd.LoadFromFile(kubeConfigPath)
if err != nil {
log.Fatal(err)
}
log.Printf("current context is %s", kubeConfig.CurrentContext)
err = clientcmd.WriteToFile(*kubeConfig, "copy.yaml")
if err != nil {
log.Fatal(err)
}
}
// findKubeConfig finds path from env:KUBECONFIG or ~/.kube/config
func findKubeConfig() (string, error) {
env := os.Getenv("KUBECONFIG")
if env != "" {
return env, nil
}
path, err := homedir.Expand("~/.kube/config")
if err != nil {
return "", err
}
return path, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment