/
kubeconfig.go
84 lines (69 loc) · 1.93 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package kubernetes
import (
"log"
"os"
"path/filepath"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
// WriteProxyKubeconfig creates a KUBECONFIG file for http proxy server. If path
// for kubeconfig is not provided then default value is create in `CWD`.
func WriteProxyKubeconfig(host, path string) (string, error) {
if path == "" {
kubeconfigPath, _, err := getKubeconfigPathInCWD()
if err != nil {
return "", err
}
path = kubeconfigPath
}
if err := restConfigToKubeconfig(&rest.Config{
Host: host,
}, path); err != nil {
return "", err
}
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
}
return absPath, nil
}
func restConfigToKubeconfig(rc *rest.Config, path string) error {
clusters := map[string]*clientcmdapi.Cluster{}
clusters["default-cluster"] = &clientcmdapi.Cluster{
Server: rc.Host,
CertificateAuthorityData: rc.TLSClientConfig.CAData,
}
contexts := map[string]*clientcmdapi.Context{}
contexts["default-context"] = &clientcmdapi.Context{
Cluster: "default-cluster",
AuthInfo: "default",
}
authinfos := map[string]*clientcmdapi.AuthInfo{}
authinfos["default"] = &clientcmdapi.AuthInfo{
ClientKeyData: rc.TLSClientConfig.KeyData,
ClientCertificateData: rc.TLSClientConfig.CertData,
}
clientConfig := clientcmdapi.Config{
Kind: "Config",
APIVersion: "v1",
Clusters: clusters,
Contexts: contexts,
CurrentContext: "default-context",
AuthInfos: authinfos,
}
return clientcmd.WriteToFile(clientConfig, path)
}
func getKubeconfigPathInCWD() (string, func(), error) {
wd, err := os.Getwd()
if err != nil {
return "", nil, err
}
kubeconfigPath := filepath.Join(wd, "support-bundle-kubeconfig")
cleanupFn := func() {
if err := os.Remove(kubeconfigPath); err != nil {
log.Println(err)
}
}
return kubeconfigPath, cleanupFn, nil
}