1
- // Package client initialize a Kubernete's client-go rest.Config
1
+ // Package client initialize a Kubernete's client-go rest.Config or clientset
2
2
package client
3
3
4
4
import (
@@ -14,31 +14,41 @@ import (
14
14
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
15
15
)
16
16
17
- // BuildConfig create a *rest.Config
18
- func BuildConfig (apiserver string , kubeconfig string ) (* rest.Config , error ) {
19
- // if we're not provided a kubeconfig path, try to find one in user's home
17
+ // NewRestConfig create a *rest.Config, using the kubectl paths and priorities:
18
+ // - Command line flags (api-server and/or kubeconfig path) have higher priorities
19
+ // - Else, use the config file path in KUBECONFIG environment variable, if any
20
+ // - Else, use the config file in ~/.kube/config, if any
21
+ // - Else, consider we're running in cluster (in a pod), and use the pod's service
22
+ // account and cluster's kubernetes.default service.
23
+ func NewRestConfig (apiserver string , kubeconfig string ) (* rest.Config , error ) {
24
+ // if not passed as an argument, kubeconfig can be provided as env var
20
25
if kubeconfig == "" {
21
- if home := homedir .HomeDir (); home != "" {
22
- if _ , err := os .Stat (filepath .Join (home , ".kube" , "config" )); err == nil {
23
- kubeconfig = filepath .Join (home , ".kube" , "config" )
24
- }
25
- }
26
+ kubeconfig = os .Getenv ("KUBECONFIG" )
26
27
}
27
28
28
- // if we're provided an api-server url, or found a kubeconfig file, use that
29
+ // if we're not provided an explicit kubeconfig path (via env, or argument),
30
+ // try to find one at the standard place (in user's home/.kube/config).
31
+ homeCfg := filepath .Join (homedir .HomeDir (), ".kube" , "config" )
32
+ _ , err := os .Stat (homeCfg )
33
+ if kubeconfig == "" && err == nil {
34
+ kubeconfig = homeCfg
35
+ }
36
+
37
+ // if we were provided or found a kubeconfig,
38
+ // or if we were provided an api-server url, use that
29
39
if apiserver != "" || kubeconfig != "" {
30
40
return clientcmd .BuildConfigFromFlags (apiserver , kubeconfig )
31
41
}
32
42
33
- // else assume we're running in cluster
43
+ // else assume we're running in a pod, in cluster
34
44
return rest .InClusterConfig ()
35
45
}
36
46
37
47
// NewClientSet create a clientset (a client connection to a Kubernetes cluster).
38
48
// It will connect using the optional apiserver or kubeconfig options, or will
39
49
// default to the automatic, in cluster settings.
40
50
func NewClientSet (apiserver string , kubeconfig string ) (* kubernetes.Clientset , error ) {
41
- config , err := BuildConfig (apiserver , kubeconfig )
51
+ config , err := NewRestConfig (apiserver , kubeconfig )
42
52
if err != nil {
43
53
return nil , err
44
54
}
0 commit comments