From 4ce43e9a3d3185fcef99c23711349e2b52ac0c06 Mon Sep 17 00:00:00 2001 From: Tom Pantelis Date: Fri, 4 Oct 2024 15:01:38 -0400 Subject: [PATCH] Add IdentfyingLabels to CreateOrUpdateWithOptions If the GenerateName field is set in the target resource, the existing resource is searched for by the target's labels. However this assumes the labels remain static for the lifetime of the resource. If the labels are updated then the existing resource is not found and a new one is created. To avoid this, allow the user to specify which labels uniquely identify the resource by adding an IdentfyingLabels field to CreateOrUpdateOptions. Signed-off-by: Tom Pantelis --- pkg/util/create_or_update_test.go | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/pkg/util/create_or_update_test.go b/pkg/util/create_or_update_test.go index da65cd71..782b2ab3 100644 --- a/pkg/util/create_or_update_test.go +++ b/pkg/util/create_or_update_test.go @@ -148,8 +148,23 @@ var _ = Describe("CreateOrUpdate function", func() { t := newCreateOrUpdateTestDiver() createOrUpdate := func(expResult util.OperationResult) error { - result, err := util.CreateOrUpdate[*unstructured.Unstructured](context.TODO(), resource.ForDynamic(t.client), - resource.MustToUnstructured(t.pod), t.mutateFn) + options := util.CreateOrUpdateOptions[*unstructured.Unstructured]{ + Client: resource.ForDynamic(t.client), + MutateOnUpdate: t.mutateFn, + } + + if t.pod.GenerateName != "" { + options.IdentifyingLabels = map[string]string{} + for k, v := range t.pod.Labels { + options.IdentifyingLabels[k] = v + } + + t.pod.Labels["new-label"] = "new-value" + } + + options.Obj = resource.MustToUnstructured(t.pod) + + result, _, err := util.CreateOrUpdateWithOptions[*unstructured.Unstructured](context.TODO(), options) if err != nil && expResult != util.OperationResultNone { return err } @@ -167,12 +182,6 @@ var _ = Describe("CreateOrUpdate function", func() { }) Context("and a mutation function specified", func() { - BeforeEach(func() { - t.pod.Name = "" - t.pod.GenerateName = "name-prefix-" - t.pod.Labels = map[string]string{"label1": "value1", "label2": "value2"} - }) - It("should invoke the function on create", func() { result, created, err := util.CreateOrUpdateWithOptions[*unstructured.Unstructured](context.TODO(), util.CreateOrUpdateOptions[*unstructured.Unstructured]{