Skip to content

Commit 050c25f

Browse files
authored
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.
1 parent e566808 commit 050c25f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

pkg/runtime/reconciler.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
corev1 "k8s.io/api/core/v1"
2727
apierrors "k8s.io/apimachinery/pkg/api/errors"
2828
"k8s.io/apimachinery/pkg/runtime/schema"
29+
"k8s.io/apimachinery/pkg/types"
2930
ctrlrt "sigs.k8s.io/controller-runtime"
3031
"sigs.k8s.io/controller-runtime/pkg/client"
3132
ctrlrtcontroller "sigs.k8s.io/controller-runtime/pkg/controller"
@@ -162,6 +163,43 @@ func (r *reconciler) SecretValueFromReference(
162163
return "", ackerr.SecretNotFound
163164
}
164165

166+
// WriteToSecret writes a value to a Secret given the namespace, name,
167+
// and key of the Secret
168+
func (r *reconciler) WriteToSecret(
169+
ctx context.Context,
170+
sourceValue string,
171+
namespace string,
172+
name string,
173+
key string,
174+
) error {
175+
176+
// Get the initial secret
177+
nsn := types.NamespacedName{
178+
Name: name,
179+
}
180+
nsn.Namespace = namespace
181+
182+
secret := &corev1.Secret{}
183+
err := r.apiReader.Get(ctx, nsn, secret)
184+
if err != nil {
185+
return ackerr.SecretNotFound
186+
}
187+
188+
// Update the field
189+
patch := client.StrategicMergeFrom(secret.DeepCopy())
190+
if secret.Data == nil {
191+
secret.Data = make(map[string][]byte, 1)
192+
}
193+
secret.Data[key] = []byte(sourceValue)
194+
195+
err = r.kc.Patch(ctx, secret, patch)
196+
if err != nil {
197+
return err
198+
}
199+
200+
return nil
201+
}
202+
165203
// Reconcile implements `controller-runtime.Reconciler` and handles reconciling
166204
// a CR CRUD request
167205
func (r *resourceReconciler) Reconcile(ctx context.Context, req ctrlrt.Request) (ctrlrt.Result, error) {

pkg/types/reconciler.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,7 @@ type Reconciler interface {
3232
// SecretValueFromReference fetches the value of a Secret given a
3333
// SecretKeyReference
3434
SecretValueFromReference(context.Context, *v1alpha1.SecretKeyReference) (string, error)
35+
// WriteToSecret writes a value to a Secret given the namespace, name,
36+
// and key of the Secret
37+
WriteToSecret(context.Context, string, string, string, string) error
3538
}

0 commit comments

Comments
 (0)