Skip to content

Commit 111139f

Browse files
committed
pkg/client/config/config.go: support merging KUBECONFIG paths
1 parent c830b03 commit 111139f

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

pkg/client/config/config.go

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ import (
2020
"flag"
2121
"fmt"
2222
"os"
23-
"os/user"
24-
"path/filepath"
2523

2624
"k8s.io/client-go/rest"
2725
"k8s.io/client-go/tools/clientcmd"
@@ -100,30 +98,30 @@ func loadConfig(context string) (*rest.Config, error) {
10098

10199
// If a flag is specified with the config location, use that
102100
if len(kubeconfig) > 0 {
103-
return loadConfigWithContext(apiServerURL, kubeconfig, context)
101+
return loadConfigWithContext(apiServerURL, &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, context)
104102
}
105-
// If an env variable is specified with the config location, use that
106-
if len(os.Getenv("KUBECONFIG")) > 0 {
107-
return loadConfigWithContext(apiServerURL, os.Getenv("KUBECONFIG"), context)
108-
}
109-
// If no explicit location, try the in-cluster config
110-
if c, err := rest.InClusterConfig(); err == nil {
111-
return c, nil
112-
}
113-
// If no in-cluster config, try the default location in the user's home directory
114-
if usr, err := user.Current(); err == nil {
115-
if c, err := loadConfigWithContext(apiServerURL, filepath.Join(usr.HomeDir, ".kube", "config"),
116-
context); err == nil {
103+
104+
// If the recommended kubeconfig env variable is not specified,
105+
// try the in-cluster config.
106+
kubeconfigPath := os.Getenv(clientcmd.RecommendedConfigPathEnvVar)
107+
if len(kubeconfigPath) == 0 {
108+
if c, err := rest.InClusterConfig(); err == nil {
117109
return c, nil
118110
}
119111
}
120112

113+
// If the recommended kubeconfig env variable is set, or there
114+
// is no in-cluster config, try the default recommended locations.
115+
if c, err := loadConfigWithContext(apiServerURL, clientcmd.NewDefaultClientConfigLoadingRules(), context); err == nil {
116+
return c, nil
117+
}
118+
121119
return nil, fmt.Errorf("could not locate a kubeconfig")
122120
}
123121

124-
func loadConfigWithContext(apiServerURL, kubeconfig, context string) (*rest.Config, error) {
122+
func loadConfigWithContext(apiServerURL string, loader clientcmd.ClientConfigLoader, context string) (*rest.Config, error) {
125123
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
126-
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
124+
loader,
127125
&clientcmd.ConfigOverrides{
128126
ClusterInfo: clientcmdapi.Cluster{
129127
Server: apiServerURL,

0 commit comments

Comments
 (0)