-
Notifications
You must be signed in to change notification settings - Fork 148
/
configmap.go
80 lines (64 loc) · 2.43 KB
/
configmap.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
package k8s
import (
"context"
"fmt"
"github.com/defenseunicorns/zarf/cli/config"
"github.com/defenseunicorns/zarf/cli/internal/message"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ReplaceConfigmap deletes and recreates a configmap
func ReplaceConfigmap(namespace, name string, labels map[string]string, data map[string][]byte) (*corev1.ConfigMap, error) {
message.Debugf("k8s.ReplaceConfigmap(%s, %s, data)", namespace, name)
if err := DeleteConfigmap(namespace, name); err != nil {
return nil, err
}
return CreateConfigmap(namespace, name, labels, data)
}
// CreateConfigmap applys a configmap to the cluster
func CreateConfigmap(namespace, name string, labels map[string]string, data map[string][]byte) (*corev1.ConfigMap, error) {
message.Debugf("k8s.CreateConfigmap(%s, %s, data)", namespace, name)
clientset := getClientset()
configMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
Labels: map[string]string{
// track the creation of this ns by zarf
config.ZarfManagedByLabel: "zarf",
},
},
BinaryData: data,
}
// Add any additional labels to the service
for key, val := range labels {
configMap.ObjectMeta.Labels[key] = val
}
createOptions := metav1.CreateOptions{}
return clientset.CoreV1().ConfigMaps(namespace).Create(context.TODO(), configMap, createOptions)
}
// DeleteConfigmap delets a confimap by name
func DeleteConfigmap(namespace, name string) error {
message.Debugf("k8s.DeleteConfigmap(%s, %s)", namespace, name)
clientSet := getClientset()
namespaceConfigmap := clientSet.CoreV1().ConfigMaps(namespace)
err := namespaceConfigmap.Delete(context.TODO(), name, metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("error deleting the configmap: %w", err)
}
return nil
}
// DeleteConfigMapsByLabel deletes a configmap by label(s)
func DeleteConfigMapsByLabel(namespace string, labels map[string]string) error {
message.Debugf("k8s.DeleteConfigMapsByLabel(%s, %v)", namespace, labels)
clientSet := getClientset()
labelSelector, _ := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
MatchLabels: labels,
})
metaOptions := metav1.DeleteOptions{}
listOptions := metav1.ListOptions{
LabelSelector: labelSelector.String(),
}
return clientSet.CoreV1().ConfigMaps(namespace).DeleteCollection(context.TODO(), metaOptions, listOptions)
}