-
Notifications
You must be signed in to change notification settings - Fork 66
/
listsecrets.go
63 lines (54 loc) · 1.94 KB
/
listsecrets.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
package connectionsecret
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/internal/kube"
)
// ListByDeploymentName returns all secrets in the specified namespace that have labels for 'projectID' and 'clusterName'
func ListByDeploymentName(ctx context.Context, k8sClient client.Client, namespace, projectID, clusterName string) ([]corev1.Secret, error) {
return list(ctx, k8sClient, namespace, projectID, clusterName, "")
}
// ListByUserName returns all secrets in the specified namespace that have label for 'projectID' and data for 'userName'
func ListByUserName(ctx context.Context, k8sClient client.Client, namespace, projectID, userName string) ([]corev1.Secret, error) {
return list(ctx, k8sClient, namespace, projectID, "", userName)
}
func list(ctx context.Context, k8sClient client.Client, namespace, projectID, clusterName, dbUserName string) ([]corev1.Secret, error) {
secrets := corev1.SecretList{}
var result []corev1.Secret
opts := &client.ListOptions{
LabelSelector: labels.SelectorFromSet(map[string]string{
TypeLabelKey: CredLabelVal,
}),
}
if namespace != "" {
opts.Namespace = namespace
}
if err := k8sClient.List(ctx, &secrets, opts); err != nil {
return nil, err
}
for _, s := range secrets.Items {
if value, ok := s.Labels[ProjectLabelKey]; !ok || value != projectID {
continue
}
if _, ok := s.Labels[ClusterLabelKey]; !ok {
continue
}
if clusterName != "" && s.Labels[ClusterLabelKey] == kube.NormalizeLabelValue(clusterName) {
result = append(result, s)
}
if dbUserName != "" {
var userName []byte
var ok bool
if userName, ok = s.Data[userNameKey]; !ok {
return nil, fmt.Errorf("secret %v is broken: missing the mandatory field %s", s.Name, userNameKey)
}
if string(userName) == dbUserName {
result = append(result, s)
}
}
}
return result, nil
}