@@ -3,12 +3,10 @@ package client
3
3
4
4
import (
5
5
"fmt"
6
- "os"
7
- "path/filepath"
8
6
9
7
"k8s.io/client-go/rest"
10
8
"k8s.io/client-go/tools/clientcmd"
11
- "k8s.io/client-go/util/homedir "
9
+ clientcmdapi "k8s.io/client-go/tools/clientcmd/api "
12
10
13
11
// Ensure we have auth plugins (gcp, azure, openstack, ...) linked in
14
12
_ "k8s.io/client-go/plugin/pkg/client/auth"
@@ -25,48 +23,28 @@ type RestClient struct {
25
23
}
26
24
27
25
// New create a new RestClient
28
- func New (apiserver , kubeconfig string ) (* RestClient , error ) {
29
- cfg , err := newRestConfig (apiserver , kubeconfig )
26
+ func New (apiserver , context , kubeconfig string ) (* RestClient , error ) {
27
+ loadingRules := clientcmd .NewDefaultClientConfigLoadingRules ()
28
+ loadingRules .ExplicitPath = kubeconfig
29
+ clientConfig := clientcmd .NewNonInteractiveDeferredLoadingClientConfig (
30
+ loadingRules ,
31
+ & clientcmd.ConfigOverrides {
32
+ ClusterInfo : clientcmdapi.Cluster {Server : apiserver },
33
+ CurrentContext : context ,
34
+ },
35
+ )
36
+
37
+ restConfig , err := clientConfig .ClientConfig ()
30
38
if err != nil {
31
39
return nil , fmt .Errorf ("failed to build a restconfig: %v" , err )
32
40
}
33
41
34
42
return & RestClient {
35
- cfg : cfg ,
43
+ cfg : restConfig ,
36
44
}, nil
37
45
}
38
46
39
47
// GetRestConfig returns the current rest.Config
40
48
func (r * RestClient ) GetRestConfig () * rest.Config {
41
49
return r .cfg
42
50
}
43
-
44
- // newRestConfig create a *rest.Config, trying to mimic kubectl behavior:
45
- // - Explicit user provided api-server (and/or kubeconfig path) have higher priorities
46
- // - Else, use the config file path in KUBECONFIG environment variable (if any)
47
- // - Else, use the config file in ~/.kube/config, if any
48
- // - Else, consider we're running in cluster (in a pod), and use the pod's service
49
- // account and cluster's kubernetes.default service.
50
- func newRestConfig (apiserver string , kubeconfig string ) (* rest.Config , error ) {
51
- // if not passed as an argument, kubeconfig can be provided as env var
52
- if kubeconfig == "" {
53
- kubeconfig = os .Getenv ("KUBECONFIG" )
54
- }
55
-
56
- // if we're not provided an explicit kubeconfig path (via env, or argument),
57
- // try to find one at the standard place (in user's home/.kube/config).
58
- homeCfg := filepath .Join (homedir .HomeDir (), ".kube" , "config" )
59
- _ , err := os .Stat (homeCfg )
60
- if kubeconfig == "" && err == nil {
61
- kubeconfig = homeCfg
62
- }
63
-
64
- // if we were provided or found a kubeconfig,
65
- // or if we were provided an api-server url, use that
66
- if apiserver != "" || kubeconfig != "" {
67
- return clientcmd .BuildConfigFromFlags (apiserver , kubeconfig )
68
- }
69
-
70
- // else assume we're running in a pod, in cluster
71
- return rest .InClusterConfig ()
72
- }
0 commit comments