k8wiz
Back to Articles

Ready to test your Kyverno knowledge? Try our Kyverno quiz!

Set Pod defaults with a Kyverno MutatingPolicy

Give Pods default resource requests and a seccomp profile with a Kyverno MutatingPolicy, using CEL ApplyConfiguration, autogen and JSONPatch.

9 min read
By k8wiz Team
  • kyverno
  • mutatingpolicy
  • cel
  • pod-security
  • resources

Platform teams often prefer filling in a sensible default over rejecting a Pod. A container with no resource requests gets scheduled as if it needs nothing, and a Pod with no seccomp profile runs unconfined. A validation policy would block those Pods and send a developer back to edit YAML. A mutating policy fixes them on the way in and leaves alone anything the author set on purpose.

Kyverno 1.20 no longer runs legacy ClusterPolicy mutate rules, so this job now belongs to MutatingPolicy in the policies.kyverno.io/v1 API. It follows the shape of the Kubernetes MutatingAdmissionPolicy and writes mutations as CEL expressions. This guide builds a Pod defaults policy step by step, explains how Kyverno extends it to Deployments and other controllers, and shows where JSONPatch fits.

Step 1: check that the CRD and webhook are ready

A MutatingPolicy runs in the Kyverno admission controller, which registers a mutating webhook with the API server. Confirm that the CRD exists and that the admission controller is running before you write a policy, because a missing controller means your defaults silently never apply.

kubectl get crd mutatingpolicies.policies.kyverno.io
kubectl -n kyverno get deployment kyverno-admission-controller

The deployment name assumes a Helm release called kyverno in the kyverno namespace. The cluster-scoped kind has the short name mpol, and there is also a NamespacedMutatingPolicy (short name nmpol) that namespace owners can create without cluster-wide rights. This guide uses the cluster-scoped kind because Pod defaults are usually a platform decision.

Step 2: choose which Pods the policy matches

spec.matchConstraints decides which requests reach the policy. It uses the same MatchResources structure as the Kubernetes admission policy types, with resourceRules, namespaceSelector and objectSelector. Here the policy matches Pod creation in every namespace except kube-system and kyverno, which you rarely want to touch.

matchConstraints:
  namespaceSelector:
    matchExpressions:
      - key: kubernetes.io/metadata.name
        operator: NotIn
        values: ["kube-system", "kyverno"]
  resourceRules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE"]
      resources: ["pods"]

The rule lists only CREATE on purpose. Kubernetes rejects most changes to the spec of a running Pod, and resource changes on a running Pod must go through the pods/resize subresource. If the policy also matched UPDATE, a harmless label change on a Pod created before the policy existed could turn into a forbidden spec change and fail.

Keep the match to a single resource rule for core v1 Pods and avoid objectSelector labels and excludeResourceRules. Kyverno only generates rules for Pod controllers when the match has that simple shape, which matters in step 5.

Step 3: let workloads opt out with a match condition

Some workloads need to keep their own settings, such as a benchmark job that should run without requests. spec.matchConditions adds CEL expressions that must all be true for the policy to run. If any condition is false, Kyverno skips the policy for that request.

matchConditions:
  - name: honor-opt-out
    expression: >-
      !has(object.metadata.labels) ||
      !('platform.example.com/defaults' in object.metadata.labels) ||
      object.metadata.labels['platform.example.com/defaults'] != 'skip'

The has() and in checks come first because CEL returns an error, not an empty value, when you index a map with a missing key. The condition is written with plain object.metadata.labels references instead of the ?labels optional syntax. Kyverno rewrites object.metadata.labels to point at the Pod template when it generates rules for Deployments, and that rewrite looks for the plain form.

Step 4: write the mutation with ApplyConfiguration

Each entry in spec.mutations has a patchType of either ApplyConfiguration or JSONPatch. An ApplyConfiguration expression returns a partial object built with Object{...} constructors, and Kyverno merges it into the incoming Pod using structured merge diff, the same merge logic as server-side apply. Lists such as spec.containers are keyed by container name, so returning a container with only a name and the fields you care about updates that container in place.

The merge sets every field your expression returns, and it does not check whether the Pod already had a value. To make a default rather than an override, each field reads the existing value when there is one and falls back to the default when there is not. Save this as pod-defaults.yaml.

apiVersion: policies.kyverno.io/v1
kind: MutatingPolicy
metadata:
  name: pod-defaults
spec:
  failurePolicy: Ignore
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "kyverno"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
  matchConditions:
    - name: honor-opt-out
      expression: >-
        !has(object.metadata.labels) ||
        !('platform.example.com/defaults' in object.metadata.labels) ||
        object.metadata.labels['platform.example.com/defaults'] != 'skip'
  mutations:
    - patchType: ApplyConfiguration
      applyConfiguration:
        expression: >-
          Object{
            spec: Object.spec{
              securityContext: Object.spec.securityContext{
                seccompProfile: Object.spec.securityContext.seccompProfile{
                  type: has(object.spec.securityContext) && has(object.spec.securityContext.seccompProfile)
                    ? object.spec.securityContext.seccompProfile.type
                    : "RuntimeDefault"
                }
              },
              containers: object.spec.containers.map(c,
                Object.spec.containers{
                  name: c.name,
                  resources: Object.spec.containers.resources{
                    requests: Object.spec.containers.resources.requests{
                      cpu: has(c.resources) && has(c.resources.requests) && has(c.resources.requests.cpu)
                        ? c.resources.requests.cpu
                        : "100m",
                      memory: has(c.resources) && has(c.resources.requests) && has(c.resources.requests.memory)
                        ? c.resources.requests.memory
                        : "128Mi"
                    }
                  }
                }
              )
            }
          }

Two choices in this file deserve a note. failurePolicy defaults to Fail, which means Pod creation stops when the expression errors or the webhook is unreachable. For defaults, a Pod without them is usually better than no Pod at all, so this policy uses Ignore. If a default is a hard requirement, pair the policy with a ValidatingPolicy that rejects what slips through.

The expression also keeps to fields the merge can change. Apply configurations may not modify atomic structs, maps or lists, because replacing them whole could delete values the author set. A container's args list is one such atomic field. If you need to set one, spec.evaluation.useServerSideApply: true switches to server-side apply semantics, which replaces the atomic value as a whole and drops anything the author had in it.

Apply the policy and wait for it to report ready.

kubectl apply -f pod-defaults.yaml
kubectl get mpol pod-defaults

The READY column comes from status.conditionStatus.ready. If it stays false, kubectl describe mpol pod-defaults shows the condition message, which is where CEL compile errors appear.

Step 5: check what autogen generated for controllers

Most Pods come from Deployments, Jobs and other controllers. A MutatingPolicy that matches Pods gets rule variants for Pod controllers by default, because spec.autogen.podControllers.enabled defaults to true. Without a controllers list, Kyverno covers DaemonSets, Deployments, ReplicaSets, StatefulSets, Jobs and CronJobs. The generated rules mutate the Pod template, so a Deployment created after the policy shows the defaults in spec.template as well.

Kyverno records the generated specs in the policy status. The defaults entry covers controllers with a spec.template, and the cronjobs entry covers the extra jobTemplate level.

kubectl get mpol pod-defaults -o jsonpath='{.status.autogen.configs.defaults.targets[*].kind}{"\n"}'

Autogen rewrites object.spec, Object.spec, object.metadata.labels and object.metadata.annotations in match conditions and ApplyConfiguration expressions. It also wraps the root Object{...} in the template path, which only works when the expression starts with Object{. That is why the expression above has no top-level ternary.

Mutating the Deployment itself has a side effect in GitOps setups, since the live template no longer matches Git. Argo CD 2.10 and later can include mutation webhooks in a server-side diff with the annotation argocd.argoproj.io/compare-options: ServerSideDiff=true,IncludeMutationWebhook=true. If you would rather only mutate Pods, list just the controllers you want or turn autogen off.

spec:
  autogen:
    podControllers:
      enabled: false

Step 6: use JSONPatch when you need exact operations

JSONPatch mutations return a list of RFC 6902 operations, built with JSONPatch{op, path, value} values. They suit cases where you need an exact add, remove, replace or test instead of a merge. Path segments that contain / or ~ must be escaped, and the jsonpatch.escapeKey() function does that for you.

Autogen does not rewrite JSONPatch expressions. It copies them unchanged into the controller variants, so a path like /metadata/annotations would land on the Deployment, not its Pod template. Put JSONPatch mutations for Pods in their own policy with autogen disabled. This one stamps each Pod with the version of the defaults it received.

apiVersion: policies.kyverno.io/v1
kind: MutatingPolicy
metadata:
  name: pod-defaults-marker
spec:
  failurePolicy: Ignore
  autogen:
    podControllers:
      enabled: false
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "kyverno"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
  mutations:
    - patchType: JSONPatch
      jsonPatch:
        expression: >-
          has(object.metadata.annotations)
          ? [
              JSONPatch{
                op: "add",
                path: "/metadata/annotations/" + jsonpatch.escapeKey("platform.example.com/defaults-version"),
                value: "v1"
              }
            ]
          : [
              JSONPatch{
                op: "add",
                path: "/metadata/annotations",
                value: {"platform.example.com/defaults-version": "v1"}
              }
            ]

The two branches exist because a JSON Patch add fails when the parent path is missing. A Pod with no annotations has no /metadata/annotations map, so the second branch creates the whole map in one operation.

Step 7: test with a server-side dry run

Kyverno processes mutation webhooks during server-side dry runs, so you can see the result without creating anything. Write a Pod that sets a memory request but no CPU request and no seccomp profile.

apiVersion: v1
kind: Pod
metadata:
  name: defaults-test
  namespace: default
spec:
  containers:
    - name: app
      image: nginx:1.27
      resources:
        requests:
          memory: "256Mi"

Run it through the API server and print the fields the policy touches.

kubectl apply --dry-run=server -f defaults-test.yaml \
  -o jsonpath='{.spec.securityContext.seccompProfile.type}{"\n"}{.spec.containers[0].resources.requests}{"\n"}'

You should see RuntimeDefault, a CPU request of 100m and the original 256Mi memory request. Add the label platform.example.com/defaults: skip to the Pod and run the command again. The match condition now fails, so neither field changes.

Why this policy leaves mutateExisting off

MutatingPolicy can also change resources that already exist, through spec.evaluation.mutateExisting.enabled, which defaults to false. When it is on and no targetMatchConstraints is set, a trigger makes the background controller mutate every existing resource that matchConstraints selects. That fits labels on Namespaces or ConfigMaps.

For Pod spec defaults it does not help. The API server would reject most of those updates on running Pods, and the background controller would need extra RBAC to try. Existing Pods pick up the defaults the next time their controller replaces them, which a rollout restart does on your schedule.

Test yourself

Ready to test your Kyverno knowledge? Try our Kyverno quiz!