-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
110 lines (97 loc) · 2.3 KB
/
client.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package ezdeploy
import (
"encoding/base64"
"errors"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"os"
"path/filepath"
"strings"
)
type KubernetesClientSource struct {
InCluster bool
KubeconfigPath string
TemporaryDir string
}
func (s KubernetesClientSource) Build() (client *kubernetes.Clientset, err error) {
var cfg *rest.Config
if s.InCluster {
if cfg, err = rest.InClusterConfig(); err != nil {
return
}
} else {
if cfg, err = clientcmd.BuildConfigFromFlags("", s.KubeconfigPath); err != nil {
return
}
}
client, err = kubernetes.NewForConfig(cfg)
return
}
func (s KubernetesClientSource) CleanUp() {
if s.TemporaryDir != "" {
_ = os.RemoveAll(s.TemporaryDir)
}
}
const (
tildePrefix = "~" + string(filepath.Separator)
)
func ResolveKubernetesClient(optKubeconfig string) (source KubernetesClientSource, err error) {
// expand kubeconfig tilde on return
defer func() {
if err != nil {
return
}
if source.KubeconfigPath == "" {
return
}
if !strings.HasPrefix(source.KubeconfigPath, tildePrefix) {
return
}
var home string
if home, err = os.UserHomeDir(); err != nil {
return
}
source.KubeconfigPath = filepath.Join(home, strings.TrimPrefix(source.KubeconfigPath, tildePrefix))
}()
var (
envKubeconfig = strings.TrimSpace(os.Getenv("KUBECONFIG"))
envKubeconfigBase64 = strings.TrimSpace(os.Getenv("KUBECONFIG_BASE64"))
)
if optKubeconfig != "" {
source.KubeconfigPath = optKubeconfig
return
}
if envKubeconfig != "" {
source.KubeconfigPath = envKubeconfig
return
}
if envKubeconfigBase64 != "" {
var buf []byte
if buf, err = base64.StdEncoding.DecodeString(envKubeconfigBase64); err != nil {
return
}
if source.TemporaryDir, err = os.MkdirTemp("", "ezdeploy-kubeconfig-*"); err != nil {
return
}
source.KubeconfigPath = filepath.Join(source.TemporaryDir, "kubeconfig")
if err = os.WriteFile(source.KubeconfigPath, buf, 0600); err != nil {
return
}
return
}
if _, err = rest.InClusterConfig(); err == nil {
source.InCluster = true
return
} else {
if !errors.Is(err, rest.ErrNotInCluster) {
return
}
}
var home string
if home, err = os.UserHomeDir(); err != nil {
return
}
source.KubeconfigPath = filepath.Join(home, ".kube", "config")
return
}