Skip to content
CNPE · Chapter 15 of 22 Day 13: Policies – validate, mutate, exceptions

Day 13: Policies – validate, mutate, exceptions

Goal: With Kyverno, first observe a rule, then enforce it, experience its side effect on running services, have pods completed automatically, and grant an exception with conditions · Duration: approx. 60 min · Prerequisite: Day 12

Briefing

  • The exam domain “Security and Policy Enforcement” asks how a platform enforces rules automatically – not via a wiki. Kyverno (installed since Day 9) knows three kinds:
Kind When Effect
ValidatingPolicy on create/update, in the background reject (Deny) or only report (Audit)
MutatingPolicy on create/update add to or change the object
GeneratingPolicy on events generate new objects (Day 9)
  • Since Kyverno 1.20 you write rules in CEL (object.spec…). Classic ClusterPolicy YAMLs from older guides are no longer executed.
  • You introduce policies in two steps: first Audit – reports show who would be affected – then Deny. If you set Deny straight away, in the worst case you take down running services. You’ll see how today.

Drill 1: Observe first

Rule: images in tenant namespaces need a fixed tag – no latest, no missing tag.

# on cp1
mkdir -p ~/cnpe/tag13 && cd ~/cnpe/tag13
cat > kein-latest.yaml <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: kein-latest
spec:
  validationActions: [Audit]           # only report
  evaluation:
    background:
      enabled: true                    # also check existing objects
  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: [v1]
      operations: [CREATE, UPDATE]
      resources: [pods]
    namespaceSelector:                 # tenants only
      matchLabels:
        tier: tenant
  variables:
  - name: container
    expression: object.spec.containers + object.spec.?initContainers.orValue([])
  validations:
  - expression: >-
      variables.container.all(c,
        c.image.contains(":") && !c.image.endsWith(":latest"))
    messageExpression: >-
      "Images brauchen einen festen Tag (nicht latest): " +
      variables.container.filter(c, !c.image.contains(":") || c.image.endsWith(":latest")).map(c, c.image).join(", ")
EOF
k apply -f kein-latest.yaml
sleep 60
k get validatingpolicy
# Reports with at least one violation (column FAIL > 0)
k get policyreport -A -o custom-columns=NS:.metadata.namespace,KIND:.scope.kind,NAME:.scope.name,PASS:.summary.pass,FAIL:.summary.fail \
  | awk 'NR==1 || $5>0'

Expected:

validatingpolicy.policies.kyverno.io/kein-latest created
NAME          AGE   READY
kein-latest   60s   true
NS          KIND         NAME                  PASS   FAIL
team-blue   ReplicaSet   api-589fc4fbcb        0      1
team-blue   ReplicaSet   api-f74849d99         0      1
team-blue   Deployment   api                   0      1
team-blue   Pod          api-f74849d99-plffp   0      1
team-blue   Pod          api-f74849d99-kfl7x   0      1

The rule only names pods – Kyverno still checks Deployments and ReplicaSets too (autogen), so that errors show up at the Deployment, not only at the pod. The one affected is api from Day 2:

# on cp1
k -n team-blue get policyreport -o json \
  | jq -r '.items[] | select(.scope.kind=="Deployment" and .scope.name=="api") | .results[] | "\(.policy) \(.result): \(.message)"'

Expected:

kein-latest fail: Images brauchen einen festen Tag (nicht latest): registry.k8s.io/hpa-example

Save your progress? Sign up for free

Drill 2: Enforce – and the side effect

You ignore the report and switch to enforcing:

# on cp1
sed -i 's/validationActions: \[Audit\]/validationActions: [Deny]/' kein-latest.yaml
k apply -f kein-latest.yaml
sleep 5
k -n team-gelb run ohne-tag --image=nginx
k -n team-gelb create deployment ohne-tag --image=nginx:latest
k -n team-gelb run mit-tag --image=nginx:1.29-alpine
k -n team-gelb delete pod mit-tag --now
# outside the tenants the rule does not apply
k -n default run frei --image=nginx --dry-run=server -o name

Expected:

validatingpolicy.policies.kyverno.io/kein-latest configured
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy kein-latest failed: Images brauchen einen festen Tag (nicht latest): nginx
error: failed to create deployment: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy kein-latest failed: Images brauchen einen festen Tag (nicht latest): nginx:latest
pod/mit-tag created
pod "mit-tag" deleted from team-gelb namespace
pod/frei

And api? It keeps running – nobody re-checks running pods. Until a pod has to be replaced:

# on cp1
# delete one pod of api – the ReplicaSet creates a replacement
k -n team-blue delete pod $(k -n team-blue get pods -l app=api -o jsonpath='{.items[0].metadata.name}') --now
sleep 15
k -n team-blue get deploy api
k -n team-blue get events --field-selector reason=FailedCreate -o custom-columns=MSG:.message --no-headers | tail -1

Expected:

pod "api-f74849d99-kfl7x" deleted from team-blue namespace
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
api    1/2     1            1           121m
Error creating: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy kein-latest failed: Images brauchen einen festen Tag (nicht latest): registry.k8s.io/hpa-example

The replacement is rejected – one node failure, one drain (Day 2), one scale-up by the HPA, and api shrinks to zero. That is why: Audit first, work through the reports, then Deny.

There is no version tag for hpa-example here. The clean solution is better anyway: pin the image by its digest – immutable, even if someone re-points the tag.

# on cp1
k -n team-blue set image deploy/api \
  api=registry.k8s.io/hpa-example@sha256:581697a37f0e136db86d6b30392f0db40ce99c8248a7044c770012f4e8491544
k -n team-blue rollout status deploy/api --timeout=120s
k -n team-blue get deploy api

Expected:

deployment.apps/api image updated
deployment "api" successfully rolled out
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
api    2/2     2            2           121m

You can get an image’s digest from crane digest, skopeo inspect or the registry itself (header Docker-Content-Digest).

Save your progress? Sign up for free

Drill 3: Mutate pods

For cost per team (Day 12), pods need the label team. Instead of demanding it from every team, the platform adds it from the namespace:

# on cp1
cat > team-label.yaml <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: MutatingPolicy
metadata:
  name: team-label
spec:
  autogen:
    podControllers:
      controllers: []                  # do not generate variants for Deployments & co. (see below)
  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: [v1]
      operations: [CREATE]
      resources: [pods]
    namespaceSelector:
      matchLabels:
        tier: tenant
  mutations:
  - patchType: ApplyConfiguration      # partial object laid over the pod
    applyConfiguration:
      expression: >-
        Object{
          metadata: Object.metadata{
            labels: Object.metadata.labels{
              team: string(namespaceObject.metadata.labels["team"])
            }
          }
        }
EOF
k apply -f team-label.yaml
sleep 5
k -n team-gelb run probe --image=nginx:1.29-alpine
k -n team-gelb get pod probe --show-labels
k -n team-gelb delete pod probe --now

Expected:

mutatingpolicy.policies.kyverno.io/team-label created
pod/probe created
NAME    READY   STATUS              RESTARTS   AGE   LABELS
probe   0/1     ContainerCreating   0          0s    run=probe,team=gelb
pod "probe" deleted from team-gelb namespace

namespaceObject is the namespace in which the object is created – CEL reads the label from it.

Without autogen.podControllers.controllers: [], Kyverno automatically carries the rule over to Deployments, StatefulSets and so on – as with the ValidatingPolicy in Drill 1. For this mutation that goes wrong: every new Deployment in a tenant namespace is then rejected with type mismatch: unexpected type name “Object.metadata”, expected “Object.spec.template.metadata”. While building this course, this was only noticed two days later, when a new Deployment could no longer be created. The pods of a Deployment still get the label – after all, they are created as pods.

Save your progress? Sign up for free

Drill 4: An exception with conditions

One of Team Gelb’s tools only exists as latest. The platform grants an exception – but only for pods named werkzeug-… and only with a ticket number. Exceptions are disabled in Kyverno; you enable them and restrict them to one namespace in which only the platform may write:

# on cp1
helm upgrade kyverno kyverno/kyverno --version 3.10.0 -n kyverno --reuse-values \
  --set features.policyExceptions.enabled=true \
  --set features.policyExceptions.namespace=kyverno-ausnahmen
k -n kyverno rollout status deploy/kyverno-admission-controller --timeout=200s
k create namespace kyverno-ausnahmen
# the webhook needs a moment after the restart
sleep 30
cat > ausnahme.yaml <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: PolicyException
metadata:
  name: werkzeug-latest
  namespace: kyverno-ausnahmen         # exceptions only take effect here
spec:
  policyRefs:
  - name: kein-latest
    kind: ValidatingPolicy
  matchConditions:                     # for which objects
  - name: nur-werkzeug-pods
    expression: object.metadata.name.startsWith('werkzeug-')
  validations:                         # compensating condition
  - expression: object.metadata.?annotations[?'plattform.lab/ticket'].orValue('') != ''
    message: Ausnahme nur mit Ticketnummer in plattform.lab/ticket
EOF
k apply -f ausnahme.yaml
sleep 10
k -n team-gelb run werkzeug-a --image=busybox --command -- sleep 600
k -n team-gelb run werkzeug-b --image=busybox --annotations=plattform.lab/ticket=PLAT-42 --command -- sleep 600
k -n team-gelb run anderer --image=busybox --annotations=plattform.lab/ticket=PLAT-42 --command -- sleep 600

Expected (abridged):

STATUS: deployed
deployment "kyverno-admission-controller" successfully rolled out
namespace/kyverno-ausnahmen created
policyexception.policies.kyverno.io/werkzeug-latest created
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy kein-latest failed: Ausnahme nur mit Ticketnummer in plattform.lab/ticket
pod/werkzeug-b created
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy kein-latest failed: Images brauchen einen festen Tag (nicht latest): busybox

Three pods, three results: rejected without a ticket, allowed with a ticket, rejected for the wrong name. If the webhook returns connection refused right after the restart, sleep 30 was too short – just repeat.

# on cp1
k -n team-gelb delete pod werkzeug-b --now

Save your progress? Sign up for free

Exercise: What do the reports say?

Time limit: 5 minutes. Team Gelb’s report lists pods with a fail – even though their images have fixed tags. Which policy reports this, and why?

Solution

# on cp1
k -n team-gelb get policyreport -o json \
  | jq -r '.items[] | select(.scope.kind=="Pod") | .scope.name as $p | .results[] | select(.result=="fail") | "\($p) \(.policy): \(.message)"' | head -3

Expected (abridged):

unbereit-7dfb7b559b-vm98x team-label: mutation is not applied
speicherfresser-6b77cb79b-kzfwp team-label: mutation is not applied
...

The MutatingPolicy only takes effect on create. Pods that were already running have no team label – the background scan reports this. Remedy without downtime: k -n team-gelb rollout restart deploy – the new pods get the label.

Save your progress? Sign up for free

Challenge

Time limit: 10 minutes. Write a ValidatingPolicy pdb-pflicht in Audit mode that requires, for Deployments in tenant namespaces with more than one replica, that a PodDisruptionBudget exists in the same namespace. Hint: CEL can read other objects with resource.List(...).

Solution

# on cp1
cat > pdb-pflicht.yaml <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: pdb-pflicht
spec:
  validationActions: [Audit]
  evaluation:
    background:
      enabled: true
  matchConstraints:
    resourceRules:
    - apiGroups: [apps]
      apiVersions: [v1]
      operations: [CREATE, UPDATE]
      resources: [deployments]
    namespaceSelector:
      matchLabels:
        tier: tenant
  variables:
  - name: podLabels
    expression: object.spec.template.metadata.?labels.orValue({})
  - name: pdbs
    expression: dyn(resource.List("policy/v1", "poddisruptionbudgets", object.metadata.namespace).items)
  validations:
  - expression: >-
      object.spec.?replicas.orValue(1) <= 1 ||
      variables.pdbs.exists(p,
        p.spec.?selector.?matchLabels.orValue({}).all(k,
          variables.podLabels[?k].orValue('') == p.spec.selector.matchLabels[k]))
    message: Deployments mit mehr als einer Kopie brauchen ein PodDisruptionBudget
EOF
k apply -f pdb-pflicht.yaml
sleep 60
k get policyreport -A -o json \
  | jq -r '.items[] | .scope.namespace as $n | .scope.name as $d | select(.scope.kind=="Deployment") | .results[] | select(.policy=="pdb-pflicht" and .result=="fail") | "\($n)/\($d)"'

Expected:

validatingpolicy.policies.kyverno.io/pdb-pflicht created
team-blue/podinfo
team-blue/web
team-gelb/unbereit
team-green/shop

api (Day 2) is missing from the list – it has a matching PDB. Two stumbling blocks when writing it: resource.List(...) returns an untyped value that CEL refuses to iterate over (expression of type ‘any’ cannot be range of a comprehension) – dyn(...) fixes that. And the direction: every entry in the PDB’s selector must appear in the pod labels, not the other way round.

Save your progress? Sign up for free

Checkpoint

# on cp1
k get validatingpolicy kein-latest -o jsonpath='{.spec.validationActions}{"\n"}'
k get mutatingpolicy team-label -o name
# full name: "policyexception" alone means the old API kyverno.io/v2
k -n kyverno-ausnahmen get policyexceptions.policies.kyverno.io -o name
k -n team-blue get deploy api -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}' | cut -c1-40

Expected:

["Deny"]
mutatingpolicy.policies.kyverno.io/team-label
policyexception.policies.kyverno.io/werkzeug-latest
registry.k8s.io/hpa-example@sha256:58169

Interview Note

  • How do you introduce a new policy? Audit, evaluate the reports, inform the teams, then Deny – and check beforehand whether running controllers (ReplicaSets, HPA) can still create pods afterwards.
  • Tag or digest? Tags can be moved, digests cannot. For reproducibility and signatures (Day 14), the digest is what counts.
  • Who may create exceptions? Only the platform, in a namespace of its own, with conditions and an expiry date – otherwise every rule becomes a recommendation.

Enterprise Note

  • Policies as code with tests (kyverno test) in CI; rollout via GitOps.
  • Evaluate PolicyReports centrally (Policy Reporter, Grafana) and show them as a metric per team.
  • Consider failurePolicy: if Kyverno goes down, should all pods be rejected (Fail) or all let through (Ignore)? Run several replicas of the admission controller.
  • Pod Security Admission (restricted) as the built-in baseline, Kyverno for everything above it.

Contents

More