From 4971c8589fe7d6d9473638fa53cde388e22426e0 Mon Sep 17 00:00:00 2001 From: Soule BA Date: Thu, 28 Mar 2024 17:55:51 +0100 Subject: [PATCH] Return a DiffTypeExclude when exclusion annotation is set in cluster We want to enable this behaviour for use cases where different controllers must coordinate in order to mutate a resource. Signed-off-by: Soule BA --- ssa/jsondiff/unstructured.go | 5 +++++ ssa/jsondiff/unstructured_test.go | 37 +++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/ssa/jsondiff/unstructured.go b/ssa/jsondiff/unstructured.go index d7458638..89aacd3b 100644 --- a/ssa/jsondiff/unstructured.go +++ b/ssa/jsondiff/unstructured.go @@ -137,6 +137,11 @@ func Unstructured(ctx context.Context, c client.Client, obj *unstructured.Unstru return nil, err } + // Short-circuit if an annotation is set to ignore the resource in-cluster. + if utils.AnyInMetadata(existingObj, o.ExclusionSelector) { + return NewDiffForUnstructured(obj, nil, DiffTypeExclude, nil), nil + } + dryRunObj := obj.DeepCopy() patchOpts := []client.PatchOption{ client.DryRunAll, diff --git a/ssa/jsondiff/unstructured_test.go b/ssa/jsondiff/unstructured_test.go index 2239db0c..5308e750 100644 --- a/ssa/jsondiff/unstructured_test.go +++ b/ssa/jsondiff/unstructured_test.go @@ -175,6 +175,43 @@ func TestUnstructuredList(t *testing.T) { } }, }, + { + name: "excludes resources with matching annotation set in the cluster", + paths: []string{ + "testdata/deployment.yaml", + "testdata/service.yaml", + }, + mutateCluster: func(obj *unstructured.Unstructured) { + if obj.GetKind() != "Service" { + return + } + + annotations := obj.GetAnnotations() + if annotations == nil { + annotations = make(map[string]string) + } + annotations["exclude"] = "enabled" + obj.SetAnnotations(annotations) + + _ = unstructured.SetNestedField(obj.Object, "NodePort", "spec", "type") + }, + opts: []ListOption{ + ExclusionSelector{"exclude": "enabled"}, + }, + want: func(desired, cluster []*unstructured.Unstructured) DiffSet { + return DiffSet{ + &Diff{ + Type: DiffTypeNone, + DesiredObject: desired[0], + ClusterObject: cluster[0], + }, + &Diff{ + Type: DiffTypeExclude, + DesiredObject: desired[1], + }, + } + }, + }, { name: "ignores JSON pointers for resources matching selector", paths: []string{