-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkubeconfig.go
63 lines (57 loc) · 1.9 KB
/
kubeconfig.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
package main
import (
"os"
"path/filepath"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/util/homedir"
)
func LoadKubeconfig(clean bool) {
home := homedir.HomeDir()
contextDirectory = filepath.Join(home, ".kube-tray", "contexts")
if _, err := os.Stat(contextDirectory); !os.IsNotExist(err) {
if clean {
os.RemoveAll(contextDirectory)
} else {
matches, _ := filepath.Glob(filepath.Join(contextDirectory, "*"))
for _, match := range matches {
ctx := filepath.Base(match)
existingContext = append(existingContext, ctx)
kubeLog.Infof("Loaded kubeconfig [%s]", ctx)
}
return
}
} else {
os.MkdirAll(contextDirectory, 0755)
}
// Load default kubeconfig
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
config, err := kubeConfig.RawConfig()
if err != nil {
kubeLog.Warning(err)
}
// Create seperate kubeconfig per context
for ctx := range config.Contexts {
user := config.Contexts[ctx].AuthInfo
newConfig := *clientcmdapi.NewConfig()
newConfig.Contexts[ctx] = config.Contexts[ctx].DeepCopy()
newConfig.AuthInfos[user] = config.AuthInfos[user].DeepCopy()
newConfig.Clusters[ctx] = config.Clusters[ctx].DeepCopy()
newConfig.CurrentContext = ctx
tmpConfigPath := filepath.Join(contextDirectory, (ctx + "tmp"))
clientcmd.WriteToFile(newConfig, tmpConfigPath)
namespaces := GetNamespaces(tmpConfigPath)
os.Remove(tmpConfigPath)
if len(namespaces) > 0 {
existingContext = append(existingContext, ctx)
kubeLog.Infof("(Re)Created kubeconfig [%s]", ctx)
for _, nsItem := range namespaces {
ns := nsItem.Name
newConfig.Contexts[ctx].Namespace = ns
clientcmd.WriteToFile(newConfig, filepath.Join(contextDirectory, ctx, ns))
}
}
}
}