-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathk8s.go
418 lines (342 loc) · 11.1 KB
/
k8s.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package main
import (
"context"
"encoding/base64"
"fmt"
api "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
defaultK8sNamespace = "default"
defaultK8sResourcePolicy = "keep"
)
type k8sObjectType string
const (
ObjectTypeSecret k8sObjectType = "Secret"
ObjectTypeConfigMap k8sObjectType = "ConfigMap"
)
type k8sSecretOptions struct {
Namespace string `long:"namespace" description:"The Kubernetes namespace the secret is located in"`
SecretName string `long:"secret-name" description:"The name of the Kubernetes secret"`
SecretKeyName string `long:"secret-key-name" description:"The name of the key/entry within the secret"`
Base64 bool `long:"base64" description:"Encode as base64 when storing and decode as base64 when reading"`
}
func (s *k8sSecretOptions) AnySet() bool {
return s.Namespace != defaultK8sNamespace || s.SecretName != "" ||
s.SecretKeyName != ""
}
type k8sConfigmapOptions struct {
Namespace string `long:"namespace" description:"The Kubernetes namespace the configmap is located in"`
Name string `long:"configmap-name" description:"The name of the Kubernetes configmap"`
KeyName string `long:"configmap-key-name" description:"The name of the key/entry within the configmap"`
}
type k8sObjectOptions struct {
Namespace string
Name string
KeyName string
Base64 bool
ObjectType k8sObjectType
}
type helmOptions struct {
Annotate bool `long:"annotate" description:"Whether Helm annotations should be added to the created secret"`
ReleaseName string `long:"release-name" description:"The value for the meta.helm.sh/release-name annotation"`
ResourcePolicy string `long:"resource-policy" description:"The value for the helm.sh/resource-policy annotation"`
}
type jsonK8sObject struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
}
func saveK8s(content string, opts *k8sObjectOptions,
overwrite bool, helm *helmOptions) error {
client, err := getClientK8s()
if err != nil {
return err
}
switch opts.ObjectType {
case ObjectTypeSecret:
return saveSecretK8s(client, content, opts, overwrite, helm)
case ObjectTypeConfigMap:
return saveConfigMapK8s(client, content, opts, overwrite, helm)
default:
return fmt.Errorf("unsupported object type: %s", opts.ObjectType)
}
}
func saveSecretK8s(client *kubernetes.Clientset, content string,
opts *k8sObjectOptions, overwrite bool, helm *helmOptions) error {
secret, exists, err := getSecretK8s(client, opts.Namespace, opts.Name)
if err != nil {
return err
}
if exists {
return updateSecretValueK8s(
client, secret, opts, overwrite, content,
)
}
return createSecretK8s(client, opts, helm, content)
}
func saveConfigMapK8s(client *kubernetes.Clientset, content string,
opts *k8sObjectOptions, overwrite bool, helm *helmOptions) error {
configMap, exists, err := getConfigMapK8s(
client, opts.Namespace, opts.Name,
)
if err != nil {
return err
}
if exists {
return updateConfigMapValueK8s(
client, configMap, opts, overwrite, content,
)
}
return createConfigMapK8s(client, opts, helm, content)
}
func readK8s(opts *k8sObjectOptions) (string, *jsonK8sObject, error) {
client, err := getClientK8s()
if err != nil {
return "", nil, err
}
switch opts.ObjectType {
case ObjectTypeSecret:
return readSecretK8s(client, opts)
default:
return "", nil, fmt.Errorf("unsupported object type: %s",
opts.ObjectType)
}
}
func readSecretK8s(client *kubernetes.Clientset,
opts *k8sObjectOptions) (string, *jsonK8sObject, error) {
// Existing logic to read a secret
secret, exists, err := getSecretK8s(
client, opts.Namespace, opts.Name,
)
if err != nil {
return "", nil, err
}
if !exists {
return "", nil, fmt.Errorf("secret %s does not exist in "+
"namespace %s", opts.Name, opts.Namespace)
}
if len(secret.Data) == 0 {
return "", nil, fmt.Errorf("secret %s exists but contains no "+
"data", opts.Name)
}
if len(secret.Data[opts.KeyName]) == 0 {
return "", nil, fmt.Errorf("secret %s exists but does not "+
"contain the key %s", opts.Name,
opts.KeyName)
}
// There is an additional layer of base64 encoding applied to each of
// the secrets. Try to de-code it now.
content, err := secretToString(
secret.Data[opts.KeyName], opts.Base64,
)
if err != nil {
return "", nil, fmt.Errorf("failed to decode raw secret %s "+
"key %s: %v", opts.Name, opts.KeyName, err)
}
return content, &jsonK8sObject{
TypeMeta: secret.TypeMeta,
ObjectMeta: secret.ObjectMeta,
}, nil
}
func getClientK8s() (*kubernetes.Clientset, error) {
log("Creating k8s cluster config")
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("unable to grab cluster config: %v", err)
}
log("Creating k8s cluster client")
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("error creating cluster config: %v", err)
}
log("Cluster client created successfully")
return client, nil
}
func getSecretK8s(client *kubernetes.Clientset, namespace,
name string) (*api.Secret, bool, error) {
log("Attempting to load secret %s from namespace %s", name, namespace)
secret, err := client.CoreV1().Secrets(namespace).Get(
context.Background(), name, metav1.GetOptions{},
)
switch {
case err == nil:
log("Secret %s loaded successfully", name)
return secret, true, nil
case errors.IsNotFound(err):
log("Secret %s not found in namespace %s", name, namespace)
return nil, false, nil
default:
return nil, false, fmt.Errorf("error querying secret "+
"existence: %v", err)
}
}
func updateSecretValueK8s(client *kubernetes.Clientset, secret *api.Secret,
opts *k8sObjectOptions, overwrite bool, content string) error {
if len(secret.Data) == 0 {
log("Data of secret %s is empty, initializing", opts.Name)
secret.Data = make(map[string][]byte)
}
if len(secret.Data[opts.KeyName]) > 0 && !overwrite {
return fmt.Errorf("key %s in secret %s already exists: %v",
opts.KeyName, opts.Name,
errTargetExists)
}
// Do we need to add an extra layer of base64?
if opts.Base64 {
content = base64.StdEncoding.EncodeToString([]byte(content))
}
secret.Data[opts.KeyName] = []byte(content)
log("Attempting to update key %s of secret %s in namespace %s",
opts.KeyName, opts.Name, opts.Namespace)
updatedSecret, err := client.CoreV1().Secrets(opts.Namespace).Update(
context.Background(), secret, metav1.UpdateOptions{},
)
if err != nil {
return fmt.Errorf("error updating secret %s in namespace %s: "+
"%v", opts.Name, opts.Namespace, err)
}
jsonSecret, _ := asJSON(jsonK8sObject{
TypeMeta: updatedSecret.TypeMeta,
ObjectMeta: updatedSecret.ObjectMeta,
})
log("Updated secret: %s", jsonSecret)
return nil
}
func createSecretK8s(client *kubernetes.Clientset, opts *k8sObjectOptions,
helm *helmOptions, content string) error {
meta := metav1.ObjectMeta{
Name: opts.Name,
}
if helm != nil && helm.Annotate {
meta.Labels = map[string]string{
"app.kubernetes.io/managed-by": "Helm",
}
meta.Annotations = map[string]string{
"helm.sh/resource-policy": helm.ResourcePolicy,
"meta.helm.sh/release-name": helm.ReleaseName,
"meta.helm.sh/release-namespace": opts.Namespace,
}
}
// Do we need to add an extra layer of base64?
if opts.Base64 {
content = base64.StdEncoding.EncodeToString([]byte(content))
}
newSecret := &api.Secret{
Type: api.SecretTypeOpaque,
ObjectMeta: meta,
Data: map[string][]byte{
opts.KeyName: []byte(content),
},
}
updatedSecret, err := client.CoreV1().Secrets(opts.Namespace).Create(
context.Background(), newSecret, metav1.CreateOptions{},
)
if err != nil {
return fmt.Errorf("error creating secret %s in namespace %s: "+
"%v", opts.Name, opts.Namespace, err)
}
jsonSecret, _ := asJSON(jsonK8sObject{
TypeMeta: updatedSecret.TypeMeta,
ObjectMeta: updatedSecret.ObjectMeta,
})
log("Created secret: %s", jsonSecret)
return nil
}
// secretToString turns the raw bytes of a secret into a string, removing the
// additional layer of base64 encoding if there is expected to be one.
func secretToString(rawSecret []byte, doubleBase64 bool) (string, error) {
content := string(rawSecret)
if doubleBase64 {
decoded, err := base64.StdEncoding.DecodeString(content)
if err != nil {
return "", fmt.Errorf("failed to base64 decode: %v",
err)
}
content = string(decoded)
}
return content, nil
}
func getConfigMapK8s(client *kubernetes.Clientset,
namespace, name string) (*api.ConfigMap, bool, error) {
log("Attempting to load configmap %s from namespace %s", name, namespace)
configMap, err := client.CoreV1().ConfigMaps(namespace).Get(
context.Background(), name, metav1.GetOptions{},
)
switch {
case err == nil:
log("ConfigMap %s loaded successfully", name)
return configMap, true, nil
case errors.IsNotFound(err):
log("ConfigMap %s not found in namespace %s", name, namespace)
return nil, false, nil
default:
return nil, false, fmt.Errorf("error querying configmap "+
"existence: %v", err)
}
}
func updateConfigMapValueK8s(client *kubernetes.Clientset,
configMap *api.ConfigMap, opts *k8sObjectOptions,
overwrite bool, content string) error {
if configMap.Data == nil {
log("Data of configmap %s is empty, initializing", opts.Name)
configMap.Data = make(map[string]string)
}
if _, exists := configMap.Data[opts.KeyName]; exists && !overwrite {
return fmt.Errorf("key %s in configmap %s already exists",
opts.KeyName, opts.Name)
}
log("Attempting to update key %s of configmap %s in namespace %s",
opts.KeyName, opts.Name, opts.Namespace)
configMap.Data[opts.KeyName] = content
updatedConfigMap, err := client.CoreV1().ConfigMaps(opts.Namespace).Update(
context.Background(), configMap, metav1.UpdateOptions{},
)
if err != nil {
return fmt.Errorf("error updating configmap %s in namespace %s: %v",
opts.Name, opts.Namespace, err)
}
jsonConfigMap, _ := asJSON(jsonK8sObject{
TypeMeta: updatedConfigMap.TypeMeta,
ObjectMeta: updatedConfigMap.ObjectMeta,
})
log("Updated configmap: %s", jsonConfigMap)
return nil
}
func createConfigMapK8s(client *kubernetes.Clientset,
opts *k8sObjectOptions, helm *helmOptions, content string) error {
meta := metav1.ObjectMeta{
Name: opts.Name,
}
if helm != nil && helm.Annotate {
meta.Labels = map[string]string{
"app.kubernetes.io/managed-by": "Helm",
}
meta.Annotations = map[string]string{
"helm.sh/resource-policy": helm.ResourcePolicy,
"meta.helm.sh/release-name": helm.ReleaseName,
"meta.helm.sh/release-namespace": opts.Namespace,
}
}
newConfigMap := &api.ConfigMap{
ObjectMeta: meta,
Data: map[string]string{
opts.KeyName: content,
},
}
updatedConfigMap, err := client.CoreV1().ConfigMaps(opts.Namespace).Create(
context.Background(), newConfigMap, metav1.CreateOptions{},
)
if err != nil {
return fmt.Errorf("error creating configmap %s in namespace %s: %v",
opts.Name, opts.Namespace, err)
}
jsonConfigMap, _ := asJSON(jsonK8sObject{
TypeMeta: updatedConfigMap.TypeMeta,
ObjectMeta: updatedConfigMap.ObjectMeta,
})
log("Created configmap: %s", jsonConfigMap)
return nil
}