forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kubeconfig.go
91 lines (75 loc) · 1.67 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
85
86
87
88
89
90
91
package kubeconfig
import (
"bytes"
"encoding/base64"
"regexp"
"github.com/rancher/rancher/pkg/settings"
)
const (
certDelim = "\\\n "
firstLen = 49
)
var (
splitRegexp = regexp.MustCompile(`\S{1,76}`)
)
type data struct {
ClusterName string
Host string
ClusterID string
Cert string
User string
Username string
Password string
Token string
}
func ForBasic(host, username, password string) (string, error) {
data := &data{
ClusterName: "cluster",
Host: host,
Cert: caCertString(),
User: username,
Username: username,
Password: password,
}
if data.ClusterName == "" {
data.ClusterName = data.ClusterID
}
buf := &bytes.Buffer{}
err := basicTemplate.Execute(buf, data)
return buf.String(), err
}
func caCertString() string {
buf := &bytes.Buffer{}
certData := settings.CACerts.Get()
if certData == "" {
return ""
}
certData = base64.StdEncoding.EncodeToString([]byte(certData))
if len(certData) > firstLen {
buf.WriteString(certData[:firstLen])
certData = certData[firstLen:]
} else {
return certData
}
for _, part := range splitRegexp.FindAllStringSubmatch(certData, -1) {
buf.WriteString(certDelim)
buf.WriteString(part[0])
}
return buf.String()
}
func ForTokenBased(clusterName, clusterID, host, username, token string) (string, error) {
data := &data{
ClusterName: clusterName,
ClusterID: clusterID,
Host: host,
Cert: caCertString(),
User: username,
Token: token,
}
if data.ClusterName == "" {
data.ClusterName = data.ClusterID
}
buf := &bytes.Buffer{}
err := tokenTemplate.Execute(buf, data)
return buf.String(), err
}