Skip to content

Commit

Permalink
Add WriteToSecret method to Reconciler interface (#128)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ndbhat authored Apr 16, 2024
1 parent e566808 commit 050c25f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
38 changes: 38 additions & 0 deletions pkg/runtime/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions pkg/types/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 050c25f

Please # to comment.