-
Notifications
You must be signed in to change notification settings - Fork 15
/
kube.go
116 lines (100 loc) · 2.11 KB
/
kube.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
111
112
113
114
115
116
package kube
import (
"fmt"
"os"
"text/template"
)
type (
kubeConfig struct {
Config string
ApiServer string
Token string
Certificate string
SkipTLS bool
Namespace string
}
Option func(*kubeConfig)
)
var tmpl = template.Must(template.New("kubeconfig").Parse(`
apiVersion: v1
kind: Config
current-context: "helm"
preferences: {}
clusters:
- name: helm
cluster:
server: {{ .ApiServer }}
{{- if eq .SkipTLS true }}
insecure-skip-tls-verify: true
{{- else if not (eq .Certificate "") }}
certificate-authority-data: {{ .Certificate }}
{{- end}}
users:
- name: helm
user:
token: {{ .Token }}
contexts:
- name: helm
context:
cluster: helm
namespace: {{ .Namespace }}
user: helm
`))
func WithConfig(config string) Option {
return func(k *kubeConfig) {
k.Config = config
}
}
func WithApiServer(apiServer string) Option {
return func(k *kubeConfig) {
k.ApiServer = apiServer
}
}
func WithToken(token string) Option {
return func(k *kubeConfig) {
k.Token = token
}
}
func WithCertificate(certificate string) Option {
return func(k *kubeConfig) {
k.Certificate = certificate
}
}
func WithSkipTLS(skipTLS bool) Option {
return func(k *kubeConfig) {
k.SkipTLS = skipTLS
}
}
func WithNamespace(namespace string) Option {
return func(k *kubeConfig) {
k.Namespace = namespace
}
}
func CreateKubeConfig(options ...Option) error {
k := &kubeConfig{}
for _, option := range options {
option(k)
}
if k.Config == "" {
return fmt.Errorf("no path to kubeconfig provided")
}
if k.ApiServer == "" {
return fmt.Errorf("no kubernetes api server provided")
}
if k.Token == "" {
return fmt.Errorf("no kubernetes token provided")
}
if k.Namespace == "" {
return fmt.Errorf("no namespace provided")
}
file, err := os.OpenFile(k.Config, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("unable to write kubeconfig: %s", err)
}
defer file.Close()
err = tmpl.Lookup("kubeconfig").Execute(file, k)
if err != nil {
return fmt.Errorf("unable to render kubeconfig: %s", err)
}
return nil
}