From 21d9a78360c39fb9faf4d574fb1290ddee9b0044 Mon Sep 17 00:00:00 2001 From: mprahl Date: Thu, 6 Apr 2023 15:05:55 -0400 Subject: [PATCH] Account for existing finalizers when adding the prune object finalizer A merge patch will overwrite the existing value. Signed-off-by: mprahl --- controllers/configurationpolicy_controller.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/controllers/configurationpolicy_controller.go b/controllers/configurationpolicy_controller.go index 906e8219..114ef0e5 100644 --- a/controllers/configurationpolicy_controller.go +++ b/controllers/configurationpolicy_controller.go @@ -719,9 +719,18 @@ func (r *ConfigurationPolicyReconciler) handleObjectTemplates(plc policyv1.Confi // set finalizer if it hasn't been set if !objHasFinalizer(&plc, pruneObjectFinalizer) { - mergePatch := []byte(`{"metadata": {"finalizers": ["` + pruneObjectFinalizer + `"]}}`) + var patch []byte + if plc.Finalizers == nil { + patch = []byte( + `[{"op":"add","path":"/metadata/finalizers","value":["` + pruneObjectFinalizer + `"]}]`, + ) + } else { + patch = []byte( + `[{"op":"add","path":"/metadata/finalizers/-","value":"` + pruneObjectFinalizer + `"}]`, + ) + } - err := r.Patch(context.TODO(), &plc, client.RawPatch(types.MergePatchType, mergePatch)) + err := r.Patch(context.TODO(), &plc, client.RawPatch(types.JSONPatchType, patch)) if err != nil { log.V(1).Error(err, "Error setting finalizer for configuration policy")