From 050c25fcef653a3b249893c2c0eac35ecc1f1863 Mon Sep 17 00:00:00 2001 From: Neha Bhat <84361901+ndbhat@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:28:37 -0400 Subject: [PATCH] Add `WriteToSecret` method to `Reconciler` interface (#128) Description of changes: WriteToSecret writes a string value to a Secret given the namespace, name, and key of the Secret By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. --- pkg/runtime/reconciler.go | 38 ++++++++++++++++++++++++++++++++++++++ pkg/types/reconciler.go | 3 +++ 2 files changed, 41 insertions(+) diff --git a/pkg/runtime/reconciler.go b/pkg/runtime/reconciler.go index 9a2409b..a9128b2 100644 --- a/pkg/runtime/reconciler.go +++ b/pkg/runtime/reconciler.go @@ -26,6 +26,7 @@ import ( corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" ctrlrt "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ctrlrtcontroller "sigs.k8s.io/controller-runtime/pkg/controller" @@ -162,6 +163,43 @@ func (r *reconciler) SecretValueFromReference( return "", ackerr.SecretNotFound } +// WriteToSecret writes a value to a Secret given the namespace, name, +// and key of the Secret +func (r *reconciler) WriteToSecret( + ctx context.Context, + sourceValue string, + namespace string, + name string, + key string, +) error { + + // Get the initial secret + nsn := types.NamespacedName{ + Name: name, + } + nsn.Namespace = namespace + + secret := &corev1.Secret{} + err := r.apiReader.Get(ctx, nsn, secret) + if err != nil { + return ackerr.SecretNotFound + } + + // Update the field + patch := client.StrategicMergeFrom(secret.DeepCopy()) + if secret.Data == nil { + secret.Data = make(map[string][]byte, 1) + } + secret.Data[key] = []byte(sourceValue) + + err = r.kc.Patch(ctx, secret, patch) + if err != nil { + return err + } + + return nil +} + // Reconcile implements `controller-runtime.Reconciler` and handles reconciling // a CR CRUD request func (r *resourceReconciler) Reconcile(ctx context.Context, req ctrlrt.Request) (ctrlrt.Result, error) { diff --git a/pkg/types/reconciler.go b/pkg/types/reconciler.go index 6821a93..d917d90 100644 --- a/pkg/types/reconciler.go +++ b/pkg/types/reconciler.go @@ -32,4 +32,7 @@ type Reconciler interface { // SecretValueFromReference fetches the value of a Secret given a // SecretKeyReference SecretValueFromReference(context.Context, *v1alpha1.SecretKeyReference) (string, error) + // WriteToSecret writes a value to a Secret given the namespace, name, + // and key of the Secret + WriteToSecret(context.Context, string, string, string, string) error }