Sub topic 5
Kyverno mutate rules
This chapter assumes you can read Kyverno ClusterPolicy YAML and know how a validate rule is structured. It also assumes you know that the API server calls mutating webhooks before validating ones.
What a mutate rule does
A mutate rule changes a resource before Kubernetes stores it. Kyverno registers a mutating admission webhook, receives the request, and returns a patch. The API server applies that patch, and then validating webhooks see the modified object.
A first mutate policy
This policy adds a managed-by label to Pods, but only if the label is not already set.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-managed-by-label
spec:
rules:
- name: add-label
match:
any:
- resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
metadata:
labels:
+(managed-by): kyvernoThe match block selects Pods, as in validate rules. The mutate.patchStrategicMerge block describes the fields to merge into the object.
The +(...) wrapper is an add-if-not-present anchor. Without it, the rule would overwrite a managed-by value that a user had set on purpose. With it, Kyverno sets the label only when the key is missing.
Choosing a patch style
Kyverno supports two ways to describe a change.
| Style | Use it when |
|---|---|
| `patchStrategicMerge` | You can describe the change as a partial copy of the resource. Best for adding labels, annotations, or fields. |
| `patchesJson6902` | You need precise operations such as `add`, `replace`, or `remove` at a specific path. Useful for list elements. |
Start with strategic merge. Move to JSON patch only when you must target an exact path.
Common errors
- Mutating but expecting rejection. Mutate rules never deny a request. If you want to block objects, add a validate rule.
- Overwriting user values. Leaving out the
+()anchor replaces existing values. Check whether the rule should respect what the user set. - Matching too broadly. A mutate rule on
Podalso touches Pods created by controllers. Narrow the match with namespaces or selectors if needed. - Forgetting existing resources. Mutation runs at admission, so objects already in the cluster stay unchanged until they are updated or recreated.
Testing the result
Run the policy locally before applying it to a cluster. The Kyverno CLI prints the patched resource.
kyverno apply add-managed-by-label.yaml --resource pod.yamlCheck that a Pod without the label gets it, and that a Pod with managed-by: helm keeps its value.
Exercise
A Pod is created with the label managed-by: helm. The policy above uses +(managed-by): kyverno. What label value does the stored Pod have, and what changes if you write managed-by: kyverno without the +() anchor?
Show answer
The stored Pod keeps managed-by: helm, because the anchor only adds the label when the key is missing. Without the anchor, the rule overwrites the value, so the stored Pod has managed-by: kyverno.