forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
53 lines (44 loc) · 1.16 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package k8s
import (
"context"
"fmt"
"io/ioutil"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func GetConfig(ctx context.Context, k8sMode string, kubeConfig string) (bool, context.Context, *rest.Config, error) {
var (
cfg *rest.Config
err error
)
switch k8sMode {
case "auto":
return getAuto(ctx, kubeConfig)
case "embedded":
return getEmbedded(ctx)
case "external":
cfg, err = getExternal(kubeConfig)
default:
return false, nil, nil, fmt.Errorf("invalid k8s-mode %s", k8sMode)
}
return false, ctx, cfg, err
}
func getAuto(ctx context.Context, kubeConfig string) (bool, context.Context, *rest.Config, error) {
if kubeConfig != "" {
cfg, err := getExternal(kubeConfig)
return false, ctx, cfg, err
}
if config, err := rest.InClusterConfig(); err == nil {
if config.BearerToken == "" {
tokenBytes, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")
if err == nil {
config.BearerToken = string(tokenBytes)
}
}
return false, ctx, config, nil
}
return getEmbedded(ctx)
}
func getExternal(kubeConfig string) (*rest.Config, error) {
return clientcmd.BuildConfigFromFlags("", kubeConfig)
}