added logic for updating the resource according to the sync flag
@@ -321,7 +321,6 @@ func applyRule(log logr.Logger, client *dclient.Client, rule kyverno.Rule, resou
// build the resource template
newResource := &unstructured.Unstructured{}
- newResourceOnlyLabel := &unstructured.Unstructured{}
newResource.SetUnstructuredContent(rdata)
newResource.SetName(genName)
newResource.SetNamespace(genNamespace)
@@ -360,14 +359,10 @@ func applyRule(log logr.Logger, client *dclient.Client, rule kyverno.Rule, resou
logger.V(2).Info("created generate target resource")
} else if mode == Update {
- if rule.Generation.Synchronize {
- label["policy.kyverno.io/synchronize"] = "enable"
- } else {
- label["policy.kyverno.io/synchronize"] = "disable"
- }
-
+ // if synchronize is true - update the label and generated resource with generate policy data
if rule.Generation.Synchronize {
logger.V(4).Info("updating existing resource")
+ label["policy.kyverno.io/synchronize"] = "enable"
newResource.SetLabels(label)
_, err := client.UpdateResource(genAPIVersion, genKind, genNamespace, newResource, false)
if err != nil {
@@ -375,14 +370,33 @@ func applyRule(log logr.Logger, client *dclient.Client, rule kyverno.Rule, resou
return noGenResource, err
}
} else {
+ // if synchronize is false - update the label in already generated resource,
+ // without comparing it with the generate policy data
+ generatedObj, err := client.GetResource(genAPIVersion, genKind, genNamespace, genName)
+ if err != nil {
+ logger.Error(err, fmt.Sprintf("generated resource not found name:%v namespace:%v kind:%v", genName, genNamespace, genKind))
+ return newGenResource, err
+ }
+
+ currentGeneratedResourcelabel := generatedObj.GetLabels()
+ currentSynclabel := currentGeneratedResourcelabel["policy.kyverno.io/synchronize"]
+
+ // update only if the labels mismatches
+ if (!rule.Generation.Synchronize && currentSynclabel == "enable") ||
+ (rule.Generation.Synchronize && currentSynclabel == "disable") {
logger.V(4).Info("updating label in existing resource")
- newResourceOnlyLabel.SetLabels(label)
- _, err := client.UpdateResource(genAPIVersion, genKind, genNamespace, newResource, false)
+ currentGeneratedResourcelabel["policy.kyverno.io/synchronize"] = "disable"
+ generatedObj.SetLabels(currentGeneratedResourcelabel)
+
+ _, err = client.UpdateResource(genAPIVersion, genKind, genNamespace, generatedObj, false)
if err != nil {
logger.Error(err, "failed to update label in existing resource")
return noGenResource, err
}
}
+
+ }
+
logger.V(2).Info("updated generate target resource")
}
