-
Notifications
You must be signed in to change notification settings - Fork 0
/
configmap.go
66 lines (53 loc) · 2.11 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2021-Present The Jackal Authors
// Package k8s provides a client for interacting with a Kubernetes cluster.
package k8s
import (
"context"
"fmt"
"github.com/defenseunicorns/pkg/helpers"
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 (k *K8s) ReplaceConfigmap(namespace, name string, data map[string][]byte) (*corev1.ConfigMap, error) {
if err := k.DeleteConfigmap(namespace, name); err != nil {
return nil, err
}
return k.CreateConfigmap(namespace, name, data)
}
// CreateConfigmap applies a configmap to the cluster.
func (k *K8s) CreateConfigmap(namespace, name string, data map[string][]byte) (*corev1.ConfigMap, error) {
configMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
BinaryData: data,
}
// Merge in common labels so that later modifications to the namespace can't mutate them
configMap.ObjectMeta.Labels = helpers.MergeMap[string](k.Labels, configMap.ObjectMeta.Labels)
createOptions := metav1.CreateOptions{}
return k.Clientset.CoreV1().ConfigMaps(namespace).Create(context.TODO(), configMap, createOptions)
}
// DeleteConfigmap deletes a configmap by name.
func (k *K8s) DeleteConfigmap(namespace, name string) error {
namespaceConfigmap := k.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 (k *K8s) DeleteConfigMapsByLabel(namespace string, labels Labels) error {
labelSelector, _ := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
MatchLabels: labels,
})
metaOptions := metav1.DeleteOptions{}
listOptions := metav1.ListOptions{
LabelSelector: labelSelector.String(),
}
return k.Clientset.CoreV1().ConfigMaps(namespace).DeleteCollection(context.TODO(), metaOptions, listOptions)
}