@@ -20,8 +20,6 @@ import (
20
20
"flag"
21
21
"fmt"
22
22
"os"
23
- "os/user"
24
- "path/filepath"
25
23
26
24
"k8s.io/client-go/rest"
27
25
"k8s.io/client-go/tools/clientcmd"
@@ -100,30 +98,30 @@ func loadConfig(context string) (*rest.Config, error) {
100
98
101
99
// If a flag is specified with the config location, use that
102
100
if len (kubeconfig ) > 0 {
103
- return loadConfigWithContext (apiServerURL , kubeconfig , context )
101
+ return loadConfigWithContext (apiServerURL , & clientcmd. ClientConfigLoadingRules { ExplicitPath : kubeconfig } , context )
104
102
}
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 {
117
109
return c , nil
118
110
}
119
111
}
120
112
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
+
121
119
return nil , fmt .Errorf ("could not locate a kubeconfig" )
122
120
}
123
121
124
- func loadConfigWithContext (apiServerURL , kubeconfig , context string ) (* rest.Config , error ) {
122
+ func loadConfigWithContext (apiServerURL string , loader clientcmd. ClientConfigLoader , context string ) (* rest.Config , error ) {
125
123
return clientcmd .NewNonInteractiveDeferredLoadingClientConfig (
126
- & clientcmd. ClientConfigLoadingRules { ExplicitPath : kubeconfig } ,
124
+ loader ,
127
125
& clientcmd.ConfigOverrides {
128
126
ClusterInfo : clientcmdapi.Cluster {
129
127
Server : apiServerURL ,
0 commit comments