Back to Practice
Lab

Kyverno Preconditions: Conditional Policies

Make a policy apply only when it should. Use a precondition — a JMESPath condition on the request — so a rule enforces resource limits on production Pods but leaves dev workloads untouched. The scalpel that keeps strict policies from breaking everything.

Your mission

A match block decides which resources a rule looks at. A precondition decides whether the rule actually fires, based on the resource's own content. The difference matters: match selects by kind/namespace/label selectors, but a precondition can test any field, with logic — "only if tier is production", "only if there's no existing owner", "only if the image is from this registry."

Preconditions are JMESPath conditions over the admission request. Each is a {key, operator, value} triple, grouped under all (AND) or any (OR):

preconditions:
  all:
    - key: "{{ request.object.metadata.labels.tier || '' }}"
      operator: Equals
      value: production

{{ ... }} is a Kyverno variable pulled from the request; the || '' gives a safe default when the label is absent. If the condition is false, the rule is skipped and the resource sails through.

This is how you run a strict policy without breaking everyone. In this lab you require CPU/memory limits — but only on production Pods — and watch a dev workload with no limits get admitted untouched.

The apps namespace is already created; Kyverno is installed.

Useful aliases

In your terminal, k is aliased to kubectl and completion is configured. The jumpbox also has k9s, jq and yq installed.

Skills you'll put into practice

kyvernopolicyadmission-controlkca

Make it your own.

Use this topic as a starting point for a fresh custom scenario.

Create a variation