Support KUBECONFIG with multiple kube config files (#1126)

* support KUBECONFIG with multiple kube config files
* use a more cross-platform friendly implementation to get the current users home dir
This commit is contained in:
Jon Carl
2019-04-01 15:25:05 +08:00
committed by Ta-Ching Chen
parent b7a41cbd89
commit 24600c20c5
4 changed files with 40 additions and 29 deletions
+30 -19
View File
@@ -19,6 +19,7 @@ package util
import (
"fmt"
"os"
"os/user"
"path/filepath"
"regexp"
"strings"
@@ -53,20 +54,6 @@ func GetFissionNamespace() string {
return fissionNamespace
}
func GetKubeConfigPath() string {
kubeConfig := os.Getenv("KUBECONFIG")
if len(kubeConfig) == 0 {
home := os.Getenv("HOME")
kubeConfig = filepath.Join(home, ".kube", "config")
if _, err := os.Stat(kubeConfig); os.IsNotExist(err) {
log.Fatal("Couldn't find kubeconfig file. " +
"Set the KUBECONFIG environment variable to your kubeconfig's path.")
}
}
return kubeConfig
}
func GetServerUrl() string {
return GetApplicationUrl("application=fission-api")
}
@@ -77,8 +64,7 @@ func GetApplicationUrl(selector string) string {
fissionUrl := os.Getenv("FISSION_URL")
if len(fissionUrl) == 0 {
fissionNamespace := GetFissionNamespace()
kubeConfig := GetKubeConfigPath()
localPort := SetupPortForward(kubeConfig, fissionNamespace, "application=fission-api")
localPort := SetupPortForward(fissionNamespace, "application=fission-api")
serverUrl = "http://127.0.0.1:" + localPort
} else {
serverUrl = fissionUrl
@@ -128,10 +114,35 @@ func KubifyName(old string) string {
return newName
}
func GetKubernetesClient(kubeConfig string) (*restclient.Config, *kubernetes.Clientset) {
config, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
// GetKubernetesClient builds a new kubernetes client. If the KUBECONFIG
// environment variable is empty or doesn't exist, ~/.kube/config is used for
// the kube config path
func GetKubernetesClient() (*restclient.Config, *kubernetes.Clientset) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeConfigPath := os.Getenv("KUBECONFIG")
if len(kubeConfigPath) == 0 {
usr, err := user.Current()
if err != nil {
log.Fatal(fmt.Sprintf("Could not get the current users directory: %s", err))
}
kubeConfigPath = filepath.Join(usr.HomeDir, ".kube", "config")
if _, err := os.Stat(kubeConfigPath); os.IsNotExist(err) {
log.Fatal("Couldn't find kubeconfig file. " +
"Set the KUBECONFIG environment variable to your kubeconfig's path.")
}
loadingRules.ExplicitPath = kubeConfigPath
log.Verbose(2, "Using kubeconfig from %q", kubeConfigPath)
} else {
log.Verbose(2, "Using kubeconfig from environment %q", kubeConfigPath)
}
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRules, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
log.Fatal(fmt.Sprintf("Failed to connect to Kubernetes: %s", err))
log.Fatal(fmt.Sprintf("Failed to build Kubernetes config: %s", err))
}
clientset, err := kubernetes.NewForConfig(config)