TRENDING
Row of white terraced houses on a green hillside in County Donegal, identical except for their front doors, which are yellow, red and pale blue
November 24, 2026
How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports
Close-up of the cutting teeth of a paper shredder packed with shredded paper and colored scraps
November 24, 2026
Dragos’s Canaries Turn AI-Router Privacy Flags Into a Measurement, and OpenRouter’s Public ZDR List Shows the Label Sat on the MiniMax and Phala Routes Through October, Its 125 Removals Reproduce as Eight Providers’ Entire Lists, and the Post Later Dropped Its Vercel and OpenRouter Example
Antique surgeon’s bone saw with a black grip and a long serrated steel blade on a pale grey background
November 24, 2026
Google Says a Suspected China-Nexus Group Exploited the vCenter Authentication Bypass in Early September, About Ten Weeks Before the Patch, but Broadcom’s Advisory Never Says It Was Exploited, the July Claim Rests on a Modifiable Build Timestamp, and the CVE Record Omits vCenter 7.0
A chalkboard covered with handwritten equations and a boxed inequality, standing for a mathematical proof
November 24, 2026
How to Prove a Rust Function Correct With Verus: Write a Spec, Read the Prover’s Errors, and Find the Bugs Tests Miss
Wooden folding rule showing a Burgos-inch scale above a centimetre scale, resting on a stone beside a lake
November 24, 2026
OpenAI’s Perplexity Proposal Turns One Internal Chart Into a Candidate Industry Limit, but Its “Cybersecurity Expert” Label Sits at 0.828, Not Below 0.8, the Millennium Prize Label Rides a November Release for a September Result, and on Open Models Per-Token Loss Hides a 2.25x Compression Gap
24 Nov 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A black missile-shaped test model mounted on a support strut inside a large concrete wind tunnel test section, with a perforated wall on the left
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
November 23, 2026
Several small yellow spirit-level bubble vials on a camera tripod head and a base plate, each bubble resting near the center
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
November 23, 2026
Rows of open sluice gates on a weir with water flowing through them, in Rožmitál pod Třemšínem, Czech Republic
Norway’s National Security Authority Tells Every Azure API Management Customer to Assume Secrets Are Out, Microsoft’s Private Notice Limits Exposure to Classic Tiers That Skipped Its Guidance, and No CVE or Public Advisory Says What the Flaw Is
November 23, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 313 Posts
News 319 Posts
Learning Hub 285 Posts
Home/Learning Hub/How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
Learning Hub

How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI

Write three Kyverno ValidatingPolicies, prove them against tricky example objects with kyverno test, measure whether your tests catch 12 planted mistakes, and run it all as a CI gate with no cluster.

November 23, 2026 34 Min Read
12

A Kubernetes cluster can refuse to run a workload that breaks your rules, but only if the rule is written correctly. This tutorial teaches you how to find out whether a rule is correct before it ever reaches a cluster. You will write three admission policies for Kyverno, test each one against example objects that include deliberately tricky cases, put the checks into a script that every pull request must pass, and then measure whether your tests would notice if someone weakened a policy. Everything runs on your own computer with one downloaded program. You do not need a cluster, Docker or a cloud account.

Table Of Content

  • The ideas you need before you start
  • Prerequisites
  • Step 1: Install the Kyverno CLI
  • Step 2: Create the project folders
  • Step 3: Write your first policy
  • What each part means
  • Step 4: Try the policy with kyverno apply
  • Step 5: Turn the surprise into a test
  • The fixtures
  • The expected results
  • Run the test against the draft policy
  • Step 6: Fix the policy until the test passes
  • Step 7: Add two more policies, each with its own tests
  • Require CPU and memory limits
  • Disallow privileged containers
  • Step 8: Check Deployments, not just Pods
  • A caveat about CronJobs
  • Step 9: Watch a test fail on purpose
  • Step 10: Run every check from one CI script
  • What the script does
  • Run it
  • Watch the script fail three ways
  • Run the script on every pull request
  • Step 11: Check that your tests would notice a weakened policy
  • Common mistakes and how to spot them
  • Policies copied from older tutorials are refused
  • A mistyped fixture name drops a test; a mistyped policy name fails loudly
  • A test run that finds no tests can exit with 0
  • A policy that matches nothing passes quietly in kyverno apply
  • Audit mode is invisible to the tests
  • A CEL error is not the same as a failure
  • Two files for the same object crash kyverno apply
  • Confirm that everything works end to end
  • Where to go next
  • Sources and further reading

A policy can be wrong in two directions. If it is too strict, it blocks a legitimate deployment at the worst possible moment. If it is too loose, it quietly lets through exactly what you wrote it to stop. Reading the YAML rarely tells you which. Running it on examples does, and that is what the Kyverno command line tool is for. Kyverno’s documentation describes it as a way to “validate and test policy behavior to resources prior to adding them to a cluster”.

The ideas you need before you start

A few short definitions will make everything else easier to follow. A Pod is the smallest thing Kubernetes runs: one or more containers that start together. A Deployment keeps several identical Pods running and replaces them when you change the image. An admission policy is a rule the cluster checks at the moment someone tries to create or change an object, before the object is stored; the rule can deny the request, or only record that the rule was broken. Kyverno is a policy engine for Kubernetes: you describe rules as YAML files and Kyverno applies them. The Kyverno CLI is a command line program that runs Kyverno’s rule engine on files, with no cluster involved.

Two more ideas matter for the tests. A fixture is a small example object you write on purpose, such as a Pod with a risky image, to see how a policy treats it. A near miss is a fixture that looks as if it should be handled one way but is handled the other. Good tests are mostly near misses.

The versions matter, so here they are. Everything below ran with Kyverno CLI v1.20.0, which GitHub lists as published on November 12, 2026, on Windows 11 with Git Bash. I ran nothing on Linux or macOS, but the same commands should work there, and only the path separators in some progress lines should differ. Many older tutorials write Kyverno policies with the kind ClusterPolicy. Kyverno v1.20 removed support for running those, and this tutorial uses the newer ValidatingPolicy, which the Kyverno documentation marks as Stable from v1.20.0. You will see the exact error message in the section on common mistakes.

Prerequisites

  • Operating system and shell: any system with a Bash-style shell. I used Windows 11 with Git Bash, which comes with Git for Windows. On Linux or macOS use your normal terminal.
  • Tools: curl and a recent Python 3 (I used 3.13.14). Python unzips the Windows download and runs one optional script near the end, which uses only the standard library.
  • Disk space: about 300 MB. The Windows archive is 48 MB and the program inside it is 252 MB, and you can delete the archive after unpacking.
  • Prior knowledge: you can read YAML (indentation and lists). You do not need to have run a cluster.
  • Not needed: a Kubernetes cluster, kubectl, Docker or any cloud account.

Step 1: Install the Kyverno CLI

The CLI is one program, so installing it means downloading one archive, unpacking it, and making sure your shell can find the program. Make a project folder first; the rest of the tutorial happens inside it. These are the commands I ran on Windows 11 in Git Bash. The export line adds the program’s folder to the search path for this terminal window only, so run it again in any new window.

mkdir -p kyverno-lab/bin
cd kyverno-lab/bin
curl -sLO https://github.com/kyverno/kyverno/releases/download/v1.20.0/kyverno-cli_v1.20.0_windows_x86_64.zip
python -c "import zipfile; zipfile.ZipFile('kyverno-cli_v1.20.0_windows_x86_64.zip').extractall('.')"
sha256sum kyverno-cli_v1.20.0_windows_x86_64.zip
cd ..
export PATH="$PWD/bin:$PATH"

GitHub shows a SHA-256 checksum for every file on the release page. The Windows archive I downloaded had 8f90ecd540b87252eb6d43702bdf2543f7fd026043b4b28de4540338cf247725, which matched. Comparing your own checksum the same way is a cheap habit before you run any downloaded program.

I did not run the Linux or macOS programs, but I downloaded the Linux x86_64 archive, confirmed that it contains a file called kyverno plus a license, and confirmed that its checksum (06b8f3ca7b5626473be8fb4d343ad54ab84e317142766f72420e7d44b80942e2) matches GitHub’s. The steps on Linux are:

mkdir -p kyverno-lab/bin
cd kyverno-lab/bin
curl -sLO https://github.com/kyverno/kyverno/releases/download/v1.20.0/kyverno-cli_v1.20.0_linux_x86_64.tar.gz
tar -xzf kyverno-cli_v1.20.0_linux_x86_64.tar.gz
sha256sum kyverno-cli_v1.20.0_linux_x86_64.tar.gz
cd ..
export PATH="$PWD/bin:$PATH"

On macOS use kyverno-cli_v1.20.0_darwin_arm64.tar.gz on Apple silicon or kyverno-cli_v1.20.0_darwin_x86_64.tar.gz on an Intel Mac, with shasum -a 256 in place of sha256sum. Now ask the program for its version. The second half of each command in this tutorial prints the exit code of the first half. An exit code of 0 means success and anything else means a problem, which is how scripts and CI jobs learn whether a command worked.

kyverno version; echo "exit code: $?"
Version: v1.20.0
Time: 2026-11-11T12:42:56Z
Git commit ID: f666af06e9bd310c7e730f1523c0430e90371a89
exit code: 0

You should see Version: v1.20.0 and an exit code of 0. If your shell says the command is not found, the export line has not run in this terminal window; run it again from the kyverno-lab folder.

Step 2: Create the project folders

Inside kyverno-lab, create four folders. Each has one job, and keeping the jobs separate is what makes the CI step at the end simple.

mkdir -p policies manifests examples tests

policies holds the rules. manifests holds the Kubernetes files your team actually ships; in a real repository it would be your deployment YAML, and here it starts with two small files. examples holds objects that are wrong on purpose, so we can demonstrate failures without putting them in the folder that CI treats as shippable. tests holds the fixtures and the expected results, with one sub-folder per policy.

Step 3: Write your first policy

We start with a rule that sounds simple: refuse any container image that does not pin a version. An image reference with no tag, or with the tag latest, can point at a different image tomorrow than it does today. Kubernetes’ own documentation says that “if you don’t specify a tag, Kubernetes assumes you mean the tag latest”. Save the file below as policies/disallow-latest-tag.yaml. It is a first draft, and it is going to have a bug.

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: disallow-latest-tag
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: >-
        object.spec.containers.all(c, c.image.contains(":") && !c.image.endsWith(":latest"))
      message: "Every image needs a tag other than latest."

What each part means

apiVersion: policies.kyverno.io/v1 and kind: ValidatingPolicy name the policy type. A ValidatingPolicy allows or denies objects. The Kyverno documentation calls it “a superset of a ValidatingAdmissionPolicy”, Kubernetes’ own built-in policy type, so it does everything that type does and more.

validationActions: [Deny] says what happens when an object breaks the rule. The Kubernetes documentation for ValidatingAdmissionPolicy defines three actions. With Deny, “Validation failure results in a denied request”. With Warn, “Validation failure is reported to the request client as a warning”. With Audit, “Validation failure is included in the audit event for the API request”. We use Deny, the strict one.

matchConstraints says which requests the policy looks at. resources: ["pods"] limits it to Pods. apiGroups: [""] means the core API group, where Pods live. operations: ["CREATE", "UPDATE"] covers creating a new Pod and changing an existing one.

validations holds the actual rule. The expression is written in CEL, the Common Expression Language, a small language for expressions that evaluate to true or false. In a validation, true means “this object is acceptable”, and when the result is false the policy reports the message. Inside the expression, object is the Pod being checked. object.spec.containers is its list of containers. .all(c, ...) is true only if the test after the comma is true for every item, where each item is called c. c.image.contains(":") is true when the image text includes a colon, and endsWith(":latest") is true when it ends with that text. Read aloud, the rule says: every container’s image must contain a colon and must not end with :latest.

Step 4: Try the policy with kyverno apply

The kyverno apply command takes policies and resource files and reports what the policies would decide. It is the quickest way to see a policy at work. We need two Pods to try it on, one that should pass and one that should not. Save the first as manifests/pod-good.yaml. It uses a pinned image and sets limits, an idea we meet in Step 7.

apiVersion: v1
kind: Pod
metadata:
  name: web
  labels:
    app: shop
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      resources:
        limits:
          cpu: 500m
          memory: 256Mi

Save the second as examples/pod-bad.yaml. It is wrong in three ways on purpose: its image comes from a private registry that has a port number and no tag, it runs privileged, and it sets no limits. Only the image rule exists so far, so only that rule can fire.

apiVersion: v1
kind: Pod
metadata:
  name: worker
  labels:
    app: shop
spec:
  containers:
    - name: worker
      image: registry.example.com:5000/shop/worker
      securityContext:
        privileged: true

Run the policy against the good Pod. The --resource flag names the file to check.

kyverno apply policies/disallow-latest-tag.yaml --resource manifests/pod-good.yaml; echo "exit code: $?"

Applying 1 policy rule(s) to 1 resource(s)...

pass: 1, fail: 0, warn: 0, error: 0, skip: 0 
exit code: 0

The summary line counts the results. We applied one policy rule to one resource and it passed, and the exit code is 0. That is what we want. Now the bad Pod:

kyverno apply policies/disallow-latest-tag.yaml --resource examples/pod-bad.yaml; echo "exit code: $?"

Applying 1 policy rule(s) to 1 resource(s)...

pass: 1, fail: 0, warn: 0, error: 0, skip: 0 
exit code: 0

The bad Pod passed too. The policy has a bug, and the exit code of 0 would let this Pod through a CI job. Nothing is wrong with the tool; the policy simply does not say what we meant. Look at the image: registry.example.com:5000/shop/worker. The colon in :5000 belongs to the registry’s port number, not to a tag, but our check only asked whether the text contains a colon. This Pod has no tag at all, so it means latest.

You now know one exit code of kyverno apply: 0 means nothing failed. We will meet 1, which means at least one resource failed a policy, in Step 7. If you get an error about a file instead of the output above, check the path you typed and the indentation of the YAML.

Step 5: Turn the surprise into a test

You could fix the policy by guesswork and look at one example again. A better habit is to write down, before changing anything, what you expect for a whole set of examples. Then a failing expectation points at the bug, and once it passes you keep a safety net for every future edit. In Kyverno each test lives in its own folder with two files: the fixtures, and a test manifest called kyverno-test.yaml.

The fixtures

Create the folder tests/disallow-latest-tag and save the Pods below as tests/disallow-latest-tag/resources.yaml. One YAML file can hold several objects separated by lines that contain only ---. I wrote them in a compact one-line style, such as {name: tagged}, so nine Pods stay readable. Each digest in the file is a made-up value of 64 zeros; nothing here pulls an image, so any well-formed digest works.

apiVersion: v1
kind: Pod
metadata: {name: tagged}
spec:
  containers:
    - {name: web, image: "nginx:1.27.2"}
---
apiVersion: v1
kind: Pod
metadata: {name: digest-only}
spec:
  containers:
    - {name: web, image: "nginx@sha256:0000000000000000000000000000000000000000000000000000000000000000"}
---
apiVersion: v1
kind: Pod
metadata: {name: tag-and-digest}
spec:
  containers:
    - {name: web, image: "nginx:1.27.2@sha256:0000000000000000000000000000000000000000000000000000000000000000"}
---
apiVersion: v1
kind: Pod
metadata: {name: host-port-tagged}
spec:
  containers:
    - {name: web, image: "registry.example.com:5000/team/web:1.2"}
---
apiVersion: v1
kind: Pod
metadata: {name: latest-with-digest}
spec:
  containers:
    - {name: web, image: "nginx:latest@sha256:0000000000000000000000000000000000000000000000000000000000000000"}
---
apiVersion: v1
kind: Pod
metadata: {name: latest}
spec:
  containers:
    - {name: web, image: "nginx:latest"}
---
apiVersion: v1
kind: Pod
metadata: {name: untagged}
spec:
  containers:
    - {name: web, image: "nginx"}
---
apiVersion: v1
kind: Pod
metadata: {name: host-port-untagged}
spec:
  containers:
    - {name: web, image: "registry.example.com:5000/team/web"}
---
apiVersion: v1
kind: Pod
metadata: {name: init-latest}
spec:
  initContainers:
    - {name: setup, image: "busybox:latest"}
  containers:
    - {name: web, image: "nginx:1.27.2"}

The table explains why each Pod exists and what the policy should do with it.

Fixture name Image in the Pod What it checks Expected
tagged nginx:1.27.2 The ordinary good case pass
digest-only nginx@sha256:0000… Pinned by digest, no tag pass
tag-and-digest nginx:1.27.2@sha256:0000… Tag and digest together pass
host-port-tagged registry.example.com:5000/team/web:1.2 A registry with a port, and a real tag pass
latest-with-digest nginx:latest@sha256:0000… The word latest, but pinned by digest pass
latest nginx:latest The obvious bad case fail
untagged nginx No tag, which means latest fail
host-port-untagged registry.example.com:5000/team/web The colon trap from Step 4 fail
init-latest app: nginx:1.27.2, init container: busybox:latest A bad image in an init container fail

The expected results

Now save the test manifest as tests/disallow-latest-tag/kyverno-test.yaml. By default kyverno test looks for a file with exactly that name in each folder it is given.

apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: disallow-latest-tag
policies:
  - ../../policies/disallow-latest-tag.yaml
resources:
  - resources.yaml
results:
  - policy: disallow-latest-tag
    kind: Pod
    resources: [tagged, digest-only, tag-and-digest, host-port-tagged, latest-with-digest]
    result: pass
  - policy: disallow-latest-tag
    kind: Pod
    resources: [latest, untagged, host-port-untagged, init-latest]
    result: fail

Read it from the top. apiVersion: cli.kyverno.io/v1alpha1 and kind: Test say this is a test manifest; the kyverno/policies repository uses the same shape for its tests. policies lists the policy files to load and resources lists the fixture files. Both paths are relative to the folder that holds the test manifest, which is why the policy path climbs out with ../../. results is the part you care about. Each entry names a policy, the kind of object, the names of the fixtures it covers and the expected result: pass means the policy accepts the object and fail means the policy rejects it. The manual page puts the idea in one sentence: the command compares “expected results, declared ahead of time in a test manifest file, to actual results reported by Kyverno”.

Run the test against the draft policy

Kyverno looks for test manifests in every folder under the path you give it, so you can point it at tests/. The real output starts with a few progress lines that name the files being loaded; I left them out here and kept the table and the summary.

kyverno test tests/; echo "exit code: $?"
│────│─────────────────────│────────────│───────────────────────────────────│────────│─────────────────────│
│ ID │ POLICY              │ RULE       │ RESOURCE                          │ RESULT │ REASON              │
│────│─────────────────────│────────────│───────────────────────────────────│────────│─────────────────────│
│ 1  │ disallow-latest-tag │ validation │ v1/Pod/default/tagged             │ Pass   │ Ok                  │
│ 2  │ disallow-latest-tag │ validation │ v1/Pod/default/digest-only        │ Pass   │ Ok                  │
│ 3  │ disallow-latest-tag │ validation │ v1/Pod/default/tag-and-digest     │ Pass   │ Ok                  │
│ 4  │ disallow-latest-tag │ validation │ v1/Pod/default/host-port-tagged   │ Pass   │ Ok                  │
│ 5  │ disallow-latest-tag │ validation │ v1/Pod/default/latest-with-digest │ Pass   │ Ok                  │
│ 6  │ disallow-latest-tag │ validation │ v1/Pod/default/latest             │ Pass   │ Ok                  │
│ 7  │ disallow-latest-tag │ validation │ v1/Pod/default/untagged           │ Pass   │ Ok                  │
│ 8  │ disallow-latest-tag │ validation │ v1/Pod/default/host-port-untagged │ Fail   │ Want fail, got pass │
│ 9  │ disallow-latest-tag │ validation │ v1/Pod/default/init-latest        │ Fail   │ Want fail, got pass │
│────│─────────────────────│────────────│───────────────────────────────────│────────│─────────────────────│


Test Summary: 7 tests passed and 2 tests failed

Error: 2 tests failed
exit code: 1

The table has one row per expectation. ID is a counter. POLICY and RESOURCE say what was checked; the resource column shows the API version, kind, namespace and name, and Kyverno fills in the namespace default because the fixtures name none. RULE says validation, the name Kyverno shows for the single check of a ValidatingPolicy. The last two columns matter most, and they describe the test, not the Pod. RESULT is Pass when your expectation matched what the policy did and Fail when it did not. REASON says why, in a form such as “Want fail, got pass”, which means you expected the policy to reject the Pod and it accepted it. Seven rows pass. Two fail, and the command exits with 1.

The first failing fixture, host-port-untagged, is the bug we saw by eye. The second is new: init-latest. An init container is a container that runs to completion before the main containers start, usually to prepare something. It pulls an image like any other container, so a latest image there is just as risky, but our draft only looked at object.spec.containers. Writing the fixture found a bug we had not noticed. That is the point of fixtures.

Step 6: Fix the policy until the test passes

Replace the contents of policies/disallow-latest-tag.yaml with this version.

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: disallow-latest-tag
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  variables:
    - name: images
      expression: >-
        object.spec.containers.map(c, parseImageReference(c.image))
        + object.spec.?initContainers.orValue([]).map(c, parseImageReference(c.image))
  validations:
    - expression: variables.images.all(i, i.containsDigest() || i.tag() != "latest")
      message: "Every image needs a tag other than latest, or a digest."

Three things changed. First, variables defines a named value, images, that the rest of the policy can reuse as variables.images. It builds a list from every container and every init container. object.spec.containers.map(c, parseImageReference(c.image)) turns each image text into an image object, and the + joins two lists. A Pod may have no init containers at all, so object.spec.?initContainers.orValue([]) asks for the field with .?, which gives an “optional” instead of an error when the field is absent, and .orValue([]) substitutes an empty list in that case.

Second, instead of hunting for colons we use parseImageReference, one of the helper functions Kyverno adds to CEL. It understands the structure of an image reference (registry, repository, tag and digest), so a port number in the registry no longer fools it. The untagged fixtures show that the parser fills in the default tag latest when none is written, just as Kubernetes does. Kyverno’s CEL library page lists this function as image(...) in its table of examples and uses parseImageReference(...) in its sample policy. I ran a one-line probe policy with each name on v1.20.0 and both rejected the same three of seven test Pods, so either works.

Third, the rule itself is now i.containsDigest() || i.tag() != "latest": an image passes if it carries a digest, or if its tag is not latest. A digest is a hash that names exactly one image, so a reference such as nginx:latest@sha256:... cannot change underneath you, and the fixture latest-with-digest expects it to pass. That is a design decision, and the fixture records it, so the next person who reads the tests can see it was intentional.

kyverno test tests/disallow-latest-tag; echo "exit code: $?"
│────│─────────────────────│────────────│───────────────────────────────────│────────│────────│
│ ID │ POLICY              │ RULE       │ RESOURCE                          │ RESULT │ REASON │
│────│─────────────────────│────────────│───────────────────────────────────│────────│────────│
│ 1  │ disallow-latest-tag │ validation │ v1/Pod/default/tagged             │ Pass   │ Ok     │
│ 2  │ disallow-latest-tag │ validation │ v1/Pod/default/digest-only        │ Pass   │ Ok     │
│ 3  │ disallow-latest-tag │ validation │ v1/Pod/default/tag-and-digest     │ Pass   │ Ok     │
│ 4  │ disallow-latest-tag │ validation │ v1/Pod/default/host-port-tagged   │ Pass   │ Ok     │
│ 5  │ disallow-latest-tag │ validation │ v1/Pod/default/latest-with-digest │ Pass   │ Ok     │
│ 6  │ disallow-latest-tag │ validation │ v1/Pod/default/latest             │ Pass   │ Ok     │
│ 7  │ disallow-latest-tag │ validation │ v1/Pod/default/untagged           │ Pass   │ Ok     │
│ 8  │ disallow-latest-tag │ validation │ v1/Pod/default/host-port-untagged │ Pass   │ Ok     │
│ 9  │ disallow-latest-tag │ validation │ v1/Pod/default/init-latest        │ Pass   │ Ok     │
│────│─────────────────────│────────────│───────────────────────────────────│────────│────────│


Test Summary: 9 tests passed and 0 tests failed
exit code: 0

All nine expectations match and the exit code is 0. Whenever you change a policy, rerun the test. It takes a fraction of a second, and it tells you at once if a fix broke something that used to work.

Step 7: Add two more policies, each with its own tests

Two more rules show different patterns. The workflow is the same for each: write the policy, write fixtures with near misses, write the expected results, run the test.

Require CPU and memory limits

A container’s limit caps how much CPU and memory it may use. Kubernetes’ documentation says that “the kubelet enforces those limits so that the running container is not allowed to use more of that resource than the limit you set”, so without limits one runaway container can starve its neighbours on the same machine. In a limit, 500m means 500 millicpu, which is half of one CPU core, and 256Mi means 256 mebibytes of memory. Save the rule as policies/require-limits.yaml.

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: require-limits
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  variables:
    - name: containers
      expression: >-
        object.spec.containers + object.spec.?initContainers.orValue([])
  validations:
    - expression: >-
        variables.containers.all(c,
          c.?resources.?limits.?cpu.hasValue() && c.?resources.?limits.?memory.hasValue())
      message: "Every container needs cpu and memory limits."

The new part is c.?resources.?limits.?cpu.hasValue(). Every .? asks for a field that might not exist. If any step along the way is missing, the whole chain becomes “no value” instead of an error, and hasValue() turns that into a plain true or false. The rule therefore reads: every container, including init containers, must have both a cpu limit and a memory limit.

The fixtures cover the full range, including three near misses: a Pod with only a CPU limit, a Pod with only a memory limit, and a Pod that sets requests (the amounts the scheduler uses to place the Pod) but no limits. Save them as tests/require-limits/resources.yaml, with the expected results in tests/require-limits/kyverno-test.yaml.

apiVersion: v1
kind: Pod
metadata: {name: limits-ok}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {limits: {cpu: 500m, memory: 256Mi}}
---
apiVersion: v1
kind: Pod
metadata: {name: limits-with-init}
spec:
  initContainers:
    - name: setup
      image: busybox:1.37
      resources: {limits: {cpu: 100m, memory: 64Mi}}
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {limits: {cpu: 500m, memory: 256Mi}}
---
apiVersion: v1
kind: Pod
metadata: {name: no-resources}
spec:
  containers:
    - {name: web, image: "nginx:1.27.2"}
---
apiVersion: v1
kind: Pod
metadata: {name: cpu-only}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {limits: {cpu: 500m}}
---
apiVersion: v1
kind: Pod
metadata: {name: memory-only}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {limits: {memory: 256Mi}}
---
apiVersion: v1
kind: Pod
metadata: {name: requests-only}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {requests: {cpu: 250m, memory: 128Mi}}
---
apiVersion: v1
kind: Pod
metadata: {name: init-without-limits}
spec:
  initContainers:
    - {name: setup, image: "busybox:1.37"}
  containers:
    - name: web
      image: nginx:1.27.2
      resources: {limits: {cpu: 500m, memory: 256Mi}}
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: require-limits
policies:
  - ../../policies/require-limits.yaml
resources:
  - resources.yaml
results:
  - policy: require-limits
    kind: Pod
    resources: [limits-ok, limits-with-init]
    result: pass
  - policy: require-limits
    kind: Pod
    resources: [no-resources, cpu-only, memory-only, requests-only, init-without-limits]
    result: fail

Disallow privileged containers

A privileged container runs with most security mechanisms switched off. The Kubernetes Pod Security Standards say it bluntly: “Privileged Pods disable most security mechanisms and must be disallowed.” Save the rule as policies/disallow-privileged.yaml.

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: disallow-privileged
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  variables:
    - name: containers
      expression: >-
        object.spec.containers + object.spec.?initContainers.orValue([])
  validations:
    - expression: >-
        variables.containers.all(c, c.?securityContext.?privileged.orValue(false) == false)
      message: "Privileged containers are not allowed."

Here c.?securityContext.?privileged.orValue(false) == false reads the optional field securityContext.privileged, treats a missing field as false, and requires the result to be false. The fixtures are a plain Pod, one with privileged: false written out, one with privileged: true, and one that is privileged only in an init container.

apiVersion: v1
kind: Pod
metadata: {name: plain}
spec:
  containers:
    - {name: web, image: "nginx:1.27.2"}
---
apiVersion: v1
kind: Pod
metadata: {name: privileged-false}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      securityContext: {privileged: false}
---
apiVersion: v1
kind: Pod
metadata: {name: privileged-true}
spec:
  containers:
    - name: web
      image: nginx:1.27.2
      securityContext: {privileged: true}
---
apiVersion: v1
kind: Pod
metadata: {name: init-privileged}
spec:
  initContainers:
    - name: setup
      image: busybox:1.37
      securityContext: {privileged: true}
  containers:
    - {name: web, image: "nginx:1.27.2"}
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: disallow-privileged
policies:
  - ../../policies/disallow-privileged.yaml
resources:
  - resources.yaml
results:
  - policy: disallow-privileged
    kind: Pod
    resources: [plain, privileged-false]
    result: pass
  - policy: disallow-privileged
    kind: Pod
    resources: [privileged-true, init-privileged]
    result: fail

With all three policies in place, apply them to the bad Pod. Passing a folder to kyverno apply loads every policy file in it.

kyverno apply policies/ --resource examples/pod-bad.yaml; echo "exit code: $?"

Applying 3 policy rule(s) to 1 resource(s)...
policy disallow-latest-tag -> resource default/Pod/worker failed:
1 - validation Every image needs a tag other than latest, or a digest.
policy disallow-privileged -> resource default/Pod/worker failed:
1 - validation Privileged containers are not allowed.
policy require-limits -> resource default/Pod/worker failed:
1 - validation Every container needs cpu and memory limits.

pass: 0, fail: 3, warn: 0, error: 0, skip: 0 
exit code: 1

Each policy reports its own failure, and the exit code is now 1: the one problem each policy was written to catch is caught. Exit code 1 is what makes a CI job fail. We will run the whole test suite after the next step.

Step 8: Check Deployments, not just Pods

In real clusters people rarely create bare Pods. They create a Deployment, which describes a pod template and lets Kubernetes create the Pods. A policy that matches only pods must still apply to the Pods a Deployment creates, or your rule has a large hole. Kyverno handles this with auto-generation: the documentation says the spec.autogen field “defines policy auto-generation behaviors, to automatically generate policies for pod controllers”. Save this Deployment, which breaks all three rules, as examples/deployment-latest.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-latest
  labels:
    app: shop
spec:
  replicas: 2
  selector:
    matchLabels:
      app: shop
  template:
    metadata:
      labels:
        app: shop
    spec:
      containers:
        - name: web
          image: nginx:latest
          securityContext:
            privileged: true
kyverno apply policies/ --resource examples/deployment-latest.yaml; echo "exit code: $?"

Applying 3 policy rule(s) to 1 resource(s)...
policy disallow-latest-tag -> resource default/Deployment/shop-latest failed:
1 - validation Every image needs a tag other than latest, or a digest.
policy disallow-privileged -> resource default/Deployment/shop-latest failed:
1 - validation Privileged containers are not allowed.
policy require-limits -> resource default/Deployment/shop-latest failed:
1 - validation Every container needs cpu and memory limits.

pass: 0, fail: 3, warn: 0, error: 0, skip: 0 
exit code: 1

None of the three policies mentions Deployments, yet all three fail on this one. The CLI in v1.20.0 evaluated the Pod rules against the Deployment’s pod template without my writing an autogen section. I checked this only in the CLI, not on a live cluster, and I did not find the default stated in the documentation, so treat the autogen field as the place to look if you need to choose which controllers a policy covers.

Now add a good Deployment to the folder of shippable manifests, so that CI has something realistic to check. Save it as manifests/deployment-good.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop
  labels:
    app: shop
spec:
  replicas: 2
  selector:
    matchLabels:
      app: shop
  template:
    metadata:
      labels:
        app: shop
    spec:
      containers:
        - name: web
          image: nginx:1.27.2
          resources:
            limits:
              cpu: 500m
              memory: 256Mi

Then add a test for Deployments in tests/deployments. It has four Deployments, one good and one for each rule, and because it covers three policies its policies list has three entries.

apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-good}
spec:
  selector: {matchLabels: {app: shop}}
  template:
    metadata: {labels: {app: shop}}
    spec:
      containers:
        - name: web
          image: nginx:1.27.2
          resources: {limits: {cpu: 500m, memory: 256Mi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-latest}
spec:
  selector: {matchLabels: {app: shop}}
  template:
    metadata: {labels: {app: shop}}
    spec:
      containers:
        - name: web
          image: nginx:latest
          resources: {limits: {cpu: 500m, memory: 256Mi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-privileged}
spec:
  selector: {matchLabels: {app: shop}}
  template:
    metadata: {labels: {app: shop}}
    spec:
      containers:
        - name: web
          image: nginx:1.27.2
          resources: {limits: {cpu: 500m, memory: 256Mi}}
          securityContext: {privileged: true}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-no-limits}
spec:
  selector: {matchLabels: {app: shop}}
  template:
    metadata: {labels: {app: shop}}
    spec:
      containers:
        - {name: web, image: "nginx:1.27.2"}
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: deployments
policies:
  - ../../policies/disallow-latest-tag.yaml
  - ../../policies/require-limits.yaml
  - ../../policies/disallow-privileged.yaml
resources:
  - resources.yaml
results:
  - policy: disallow-latest-tag
    kind: Deployment
    resources: [shop-good]
    result: pass
  - policy: disallow-latest-tag
    kind: Deployment
    resources: [shop-latest]
    result: fail
  - policy: require-limits
    kind: Deployment
    resources: [shop-good]
    result: pass
  - policy: require-limits
    kind: Deployment
    resources: [shop-no-limits]
    result: fail
  - policy: disallow-privileged
    kind: Deployment
    resources: [shop-good]
    result: pass
  - policy: disallow-privileged
    kind: Deployment
    resources: [shop-privileged]
    result: fail
kyverno test tests/deployments; echo "exit code: $?"
│────│─────────────────────│────────────│────────────────────────────────────────────│────────│────────│
│ ID │ POLICY              │ RULE       │ RESOURCE                                   │ RESULT │ REASON │
│────│─────────────────────│────────────│────────────────────────────────────────────│────────│────────│
│ 1  │ disallow-latest-tag │ validation │ apps/v1/Deployment/default/shop-good       │ Pass   │ Ok     │
│ 2  │ disallow-latest-tag │ validation │ apps/v1/Deployment/default/shop-latest     │ Pass   │ Ok     │
│ 3  │ require-limits      │ validation │ apps/v1/Deployment/default/shop-good       │ Pass   │ Ok     │
│ 4  │ require-limits      │ validation │ apps/v1/Deployment/default/shop-no-limits  │ Pass   │ Ok     │
│ 5  │ disallow-privileged │ validation │ apps/v1/Deployment/default/shop-good       │ Pass   │ Ok     │
│ 6  │ disallow-privileged │ validation │ apps/v1/Deployment/default/shop-privileged │ Pass   │ Ok     │
│────│─────────────────────│────────────│────────────────────────────────────────────│────────│────────│


Test Summary: 6 tests passed and 0 tests failed
exit code: 0

Now run the whole suite. This is the command you will run most often from here on. The real output holds four tables, one for each test folder, so I show only the end of it.

kyverno test tests/; echo "exit code: $?"
Test Summary: 26 tests passed and 0 tests failed
exit code: 0

Twenty-six tests match: nine for the image rule, seven for limits, four for privileged containers and six for Deployments.

A caveat about CronJobs

I tried a CronJob fixture as well and left it out of the lab on purpose. With one policy and one CronJob fixture, the table sometimes had an extra row marked Excluded, which inflated the test count. It appeared in 5 of 40 repeats of the same files, and the verdicts in the other rows did not change. With Deployments only, every one of 40 repeats of the full suite printed the same count. If you add CronJobs, the count check in the CI script of Step 10 becomes unreliable, so keep CronJobs out of the counted tests or drop that check.

Step 9: Watch a test fail on purpose

A test suite you have never seen fail is a suite you cannot fully trust. Open tests/disallow-latest-tag/kyverno-test.yaml and temporarily move latest from the fail list to the pass list, so that the two entries read like this:

  - policy: disallow-latest-tag
    kind: Pod
    resources: [tagged, digest-only, tag-and-digest, host-port-tagged, latest-with-digest, latest]
    result: pass
  - policy: disallow-latest-tag
    kind: Pod
    resources: [untagged, host-port-untagged, init-latest]
    result: fail

That claims a Pod using nginx:latest should be accepted, which is false. Run the test with --fail-only, a flag that prints only the failing rows.

kyverno test tests/disallow-latest-tag --fail-only; echo "exit code: $?"
Aggregated Failed Test Cases : 
│────│─────────────────────│────────────│───────────────────────│────────│─────────────────────│
│ ID │ POLICY              │ RULE       │ RESOURCE              │ RESULT │ REASON              │
│────│─────────────────────│────────────│───────────────────────│────────│─────────────────────│
│ 1  │ disallow-latest-tag │ validation │ v1/Pod/default/latest │ Fail   │ Want pass, got fail │
│────│─────────────────────│────────────│───────────────────────│────────│─────────────────────│
Error: 1 tests failed
exit code: 1

The table names the exact fixture and says Want pass, got fail, and the command exits with 1. Put latest back in the fail list before you continue.

Step 10: Run every check from one CI script

Continuous integration, or CI, means a server runs your checks automatically on every change, so a broken rule or a bad manifest is caught in the pull request instead of in production. The Kyverno documentation describes two uses of the CLI in CI: testing resources you do not control against policies you know, and checking that policies and resources keep producing predefined outcomes. We will do both, plus one guard that the tests cannot provide. Save this as ci.sh.

#!/usr/bin/env bash
# ci.sh: the checks a pull request must pass. Needs the kyverno CLI on PATH and no cluster.
set -euo pipefail

echo "== 1. Do the manifests we ship pass the policies?"
kyverno apply policies/ --resource manifests/

echo "== 2. Do the policies still behave the way the tests say?"
kyverno test tests/ --require-tests | tee test-run.txt
# A mistyped resource name in a results list is dropped without an error, so count the expectations.
expected=$(grep -h -E '^ +resources: \[' tests/*/kyverno-test.yaml | sed -E 's/.*\[(.*)\].*/\1/' | tr ',' '\n' | grep -c .)
if ! grep -q "Test Summary: $expected tests passed and 0 tests failed" test-run.txt; then
  echo "Expected $expected passing tests, see test-run.txt"
  exit 1
fi

echo "== 3. Is every policy set to Deny?"
weak=$(grep -L -E '^  validationActions: \[Deny\]$' policies/*.yaml || true)
if [ -n "$weak" ]; then
  echo "Not set to Deny: $weak"
  exit 1
fi
echo "ci.sh: all checks passed"

What the script does

The line set -euo pipefail makes the script stop at the first failing command, treat unset variables as errors, and fail a pipeline when any part of it fails. That is what turns a Kyverno exit code of 1 into a failed CI job.

Check 1 runs kyverno apply on the shipped manifests. It answers the question: do the objects we actually deploy obey the rules? Check 2 runs kyverno test on the fixtures. It answers a different question: do the rules still behave the way the tests say? The flag --require-tests makes the command fail when it finds no test at all, which matters because, as the section on common mistakes shows, a test run that finds nothing otherwise exits with 0. The output is also saved to test-run.txt, so add that file name to your .gitignore. The next lines count the names listed in the result entries and demand that exactly that many tests passed, because a mistyped fixture name is dropped silently. Check 3 is a plain text guard: it lists policy files that do not contain the line validationActions: [Deny] and fails if there are any. The tests cannot see that setting, and Step 11 shows why that matters.

Run it

On a clean project all three checks pass. The output is long because it includes the test tables, so I show the first lines and then the end.

bash ci.sh; echo "exit code: $?"
== 1. Do the manifests we ship pass the policies?

Applying 3 policy rule(s) to 2 resource(s)...

pass: 6, fail: 0, warn: 0, error: 0, skip: 0 
== 2. Do the policies still behave the way the tests say?
== 3. Is every policy set to Deny?
ci.sh: all checks passed
exit code: 0

Watch the script fail three ways

First, pretend a teammate adds a Deployment that breaks the rules to the folder of shippable manifests. Copy our bad example there:

cp examples/deployment-latest.yaml manifests/
bash ci.sh; echo "exit code: $?"
== 1. Do the manifests we ship pass the policies?

Applying 3 policy rule(s) to 3 resource(s)...
policy disallow-latest-tag -> resource default/Deployment/shop-latest failed:
1 - validation Every image needs a tag other than latest, or a digest.
policy disallow-privileged -> resource default/Deployment/shop-latest failed:
1 - validation Privileged containers are not allowed.
policy require-limits -> resource default/Deployment/shop-latest failed:
1 - validation Every container needs cpu and memory limits.

pass: 6, fail: 3, warn: 0, error: 0, skip: 0 
exit code: 1

Check 1 fails and the script stops there. The new Deployment fails all three policies, and the exit code is 1. Delete the copy with rm manifests/deployment-latest.yaml.

Second, mistype a fixture name in a result list: write latesst instead of latest in the fail list of tests/disallow-latest-tag/kyverno-test.yaml. Kyverno does not complain about the unknown name; it just runs one test fewer. The script counts and notices. Undo the typo afterwards.

bash ci.sh; echo "exit code: $?"

Test Summary: 25 tests passed and 0 tests failed

Expected 26 passing tests, see test-run.txt
exit code: 1

Third, change [Deny] to [Audit] in policies/require-limits.yaml. Checks 1 and 2 still pass, because neither can see the setting, and check 3 catches it. Change it back afterwards.

bash ci.sh; echo "exit code: $?"
== 3. Is every policy set to Deny?
Not set to Deny: policies/require-limits.yaml
exit code: 1

Run the script on every pull request

On GitHub, a workflow file in .github/workflows/ can run the script for each pull request. This is based on the example in the Kyverno documentation: I changed the CLI version to v1.20.0 and replaced its last steps with a single step that runs ci.sh. It uses the kyverno/action-install-cli action at v0.2.0, the latest tag of that action, whose release input selects the CLI version. I could not run GitHub Actions here, so treat the workflow itself as untested; it only wraps the script you just ran.

name: kyverno-policy-test
on:
  - pull_request
  - workflow_dispatch
jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
      - name: Install Kyverno CLI
        uses: kyverno/[email protected]
        with:
          release: 'v1.20.0'
      - name: Run the policy checks
        run: bash ci.sh

Step 11: Check that your tests would notice a weakened policy

Passing tests prove that the policies and the tests agree today. They do not prove the tests would notice if someone later weakened a policy. A simple way to find out is mutation testing: copy the project, plant one deliberate mistake in a policy, run the checks, and see whether anything turns red. A mistake the checks do not notice is a hole in your suite. Save the script below as mutants.py. It plants twelve mistakes, one at a time, each in a throwaway copy of the project.

# mutants.py: plant one mistake at a time in a copy of the lab and report whether the checks notice it.
# Needs the kyverno CLI on PATH. Standard library only. Run with: python -I mutants.py
import pathlib
import shutil
import subprocess
import sys
import tempfile

LAB = pathlib.Path(__file__).resolve().parent
INIT_LINE = "        + object.spec.?initContainers.orValue([]).map(c, parseImageReference(c.image))\n"
CONTAINERS = "        object.spec.containers + object.spec.?initContainers.orValue([])\n"

# (label, policy file, exact text to replace, replacement)
MUTANTS = [
    ("latest: init containers skipped", "disallow-latest-tag.yaml", INIT_LINE, ""),
    ("latest: != turned into ==", "disallow-latest-tag.yaml", 'i.tag() != "latest"', 'i.tag() == "latest"'),
    ("latest: digest exemption removed", "disallow-latest-tag.yaml", "i.containsDigest() || ", ""),
    ("latest: only jobs get the autogen copy", "disallow-latest-tag.yaml", "  variables:\n",
     "  autogen:\n    podControllers:\n      controllers: [jobs]\n  variables:\n"),
    ("limits: memory not required", "require-limits.yaml", " && c.?resources.?limits.?memory.hasValue()", ""),
    ("limits: init containers skipped", "require-limits.yaml", CONTAINERS, "        object.spec.containers\n"),
    ("limits: reads requests instead of limits", "require-limits.yaml", "?limits.?cpu", "?requests.?cpu"),
    ("privileged: init containers skipped", "disallow-privileged.yaml", CONTAINERS, "        object.spec.containers\n"),
    ("privileged: field typo (privilege)", "disallow-privileged.yaml", "?privileged", "?privilege"),
    ("privileged: resource name typo (pod)", "disallow-privileged.yaml", 'resources: ["pods"]', 'resources: ["pod"]'),
    ("latest: field typo in the expression (imagee)", "disallow-latest-tag.yaml", "c, parseImageReference(c.image))\n        +", "c, parseImageReference(c.imagee))\n        +"),
    ("latest: Deny turned into Audit", "disallow-latest-tag.yaml", "[Deny]", "[Audit]"),
]


def run(args, cwd):
    done = subprocess.run(["kyverno", *args], cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace")
    return done.returncode


def main():
    caught_tests = caught_apply = caught_guard = 0
    print(f"{'mutant':46} {'kyverno test':13} {'kyverno apply':14} {'Deny guard'}")
    for label, name, old, new in MUTANTS:
        with tempfile.TemporaryDirectory() as tmp:
            work = pathlib.Path(tmp) / "lab"
            shutil.copytree(LAB, work, ignore=shutil.ignore_patterns("bin", "out", "__pycache__", "scratch", "test-run.txt"))
            target = work / "policies" / name
            text = target.read_text(encoding="utf-8")
            if text.count(old) != 1:
                sys.exit(f"{label}: the text to replace occurs {text.count(old)} times in {name}")
            target.write_text(text.replace(old, new), encoding="utf-8", newline="\n")
            t = run(["test", "tests/", "--require-tests"], work) != 0
            a = run(["apply", "policies/", "--resource", "manifests/"], work) != 0
            g = "validationActions: [Deny]" not in (target.read_text(encoding="utf-8"))
        caught_tests += t
        caught_apply += a
        caught_guard += g
        word = lambda hit: "caught" if hit else "missed"
        print(f"{label:46} {word(t):13} {word(a):14} {word(g)}")
    total = len(MUTANTS)
    print(f"caught: tests {caught_tests} of {total}, apply on shipped manifests {caught_apply} of {total}, Deny guard {caught_guard} of {total}")


main()

Each mutant is a policy file name, the exact text to replace and its replacement. The script refuses to run if the text does not occur exactly once, so a typo in the table cannot silently plant nothing. The copy skips the bin folder, so the large program is not copied twelve times. For each mutant it runs three checks: kyverno test, kyverno apply on the shipped manifests, and the Deny guard, which is the same condition as check 3 of the CI script. Use python3 instead of python if that is the name on your system. The whole run took about seven seconds on my machine.

python -I mutants.py; echo "exit code: $?"
mutant                                         kyverno test  kyverno apply  Deny guard
latest: init containers skipped                caught        missed         missed
latest: != turned into ==                      caught        caught         missed
latest: digest exemption removed               caught        missed         missed
latest: only jobs get the autogen copy         caught        missed         missed
limits: memory not required                    caught        missed         missed
limits: init containers skipped                caught        missed         missed
limits: reads requests instead of limits       caught        caught         missed
privileged: init containers skipped            caught        missed         missed
privileged: field typo (privilege)             caught        missed         missed
privileged: resource name typo (pod)           caught        missed         missed
latest: field typo in the expression (imagee)  caught        caught         missed
latest: Deny turned into Audit                 missed        missed         caught
caught: tests 11 of 12, apply on shipped manifests 3 of 12, Deny guard 1 of 12
exit code: 0

The last line is the lesson. The tests caught 11 of the 12 mistakes. Running kyverno apply on the shipped manifests caught only 3. It can only notice a mistake that makes a good manifest fail, such as flipping a comparison, reading the wrong field, or an expression that errors, because every shipped manifest is already good. A policy that silently stops checking anything passes every shipped manifest. The mutant that writes privilege instead of privileged is one of these: a misspelled optional field is just a missing field, so orValue(false) hands back false for every Pod. The mutant that spells the resource as pod is another: it matches nothing. Only fixtures that are supposed to be rejected can catch these, which is why a suite needs both kinds of check.

The one mistake the tests missed is the last one, changing Deny to Audit. The fixtures still produce the same verdicts, because a unit test checks what the expression decides, not what the cluster does with the decision. The Deny guard catches it, and between the three checks every mutant is caught at least once.

Common mistakes and how to spot them

Each item below is something I measured on v1.20.0 while building the lab. Together they explain why the CI script has the extra lines it has.

Policies copied from older tutorials are refused

Older posts and examples use kind: ClusterPolicy under apiVersion: kyverno.io/v1. Save this typical one as legacy/disallow-latest-tag.yaml to try it.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-latest-tag
spec:
  validationFailureAction: Enforce
  background: true
  rules:
    - name: require-image-tag
      match:
        any:
          - resources:
              kinds: [Pod]
      validate:
        message: "An image tag is required."
        pattern:
          spec:
            containers:
              - image: "*:*"
kyverno apply legacy/disallow-latest-tag.yaml --resource examples/pod-bad.yaml; echo "exit code: $?"
Error: failed to load file legacy/disallow-latest-tag.yaml: failed to process kyverno.io/v1, Kind=ClusterPolicy: kyverno.io/v1 ClusterPolicy: Kyverno v1.20 removed execution of legacy kyverno.io policy types and no longer accepts create or update requests for them; the API remains available for read, list, export, and delete. Migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/
exit code: 1

The CLI exits with 1 and prints that Kyverno v1.20 removed the execution of legacy policy types, and it points to a migration guide. Adding --warnings-as-errors changes nothing, because this is already an error. Rewrite such a policy as a ValidatingPolicy, as we did in Step 6, or as one of the other new types the message names.

A mistyped fixture name drops a test; a mistyped policy name fails loudly

With latesst in the fail list, run the latest-tag test folder on its own:

kyverno test tests/disallow-latest-tag; echo "exit code: $?"
Test Summary: 8 tests passed and 0 tests failed
exit code: 0

The summary says 8 tests passed instead of 9, and the exit code is 0. The fixture named latesst matches nothing, so its expectation disappears and the real latest fixture is no longer checked at all. A mistyped policy name behaves differently. If the test manifest says disallow-latest-tagg in the fail entry, the four fixtures in that entry fail with the reason Not found:

kyverno test tests/disallow-latest-tag; echo "exit code: $?"
│ 7  │ disallow-latest-tagg │            │ v1/Pod/default/untagged           │ Fail   │ Not found │
│ 8  │ disallow-latest-tagg │            │ v1/Pod/default/host-port-untagged │ Fail   │ Not found │
│ 9  │ disallow-latest-tagg │            │ v1/Pod/default/init-latest        │ Fail   │ Not found │
│────│──────────────────────│────────────│───────────────────────────────────│────────│───────────│


Test Summary: 5 tests passed and 4 tests failed

Error: 4 tests failed
exit code: 1

A test run that finds no tests can exit with 0

Point kyverno test at a folder that has no test manifest, for example policies/:

kyverno test policies/; echo "exit code: $?"

No test yamls available
exit code: 0

It prints a notice and exits with 0, so a CI job with a wrong path would pass without testing anything. The --require-tests flag, which the manual describes as returning “an error if no tests are found”, turns that into a failure:

kyverno test policies/ --require-tests; echo "exit code: $?"

No test yamls available
Error: no tests found
exit code: 1

A path that does not exist at all is already an error with exit code 1.

A policy that matches nothing passes quietly in kyverno apply

Change resources: ["pods"] to resources: ["pod"] in policies/disallow-privileged.yaml, a one-letter typo that makes the policy match nothing. Then apply all three policies to the bad Pod, which is privileged:

kyverno apply policies/ --resource examples/pod-bad.yaml; echo "exit code: $?"

Applying 3 policy rule(s) to 1 resource(s)...
policy disallow-latest-tag -> resource default/Pod/worker failed:
1 - validation Every image needs a tag other than latest, or a digest.
policy require-limits -> resource default/Pod/worker failed:
1 - validation Every container needs cpu and memory limits.

pass: 0, fail: 2, warn: 0, error: 0, skip: 0 
exit code: 1

Only two failures appear, and nothing mentions the third policy. The test is much louder, as the mutant table showed:

kyverno test tests/disallow-privileged; echo "exit code: $?"
│────│─────────────────────│──────│─────────────────────────────────│────────│───────────│
│ ID │ POLICY              │ RULE │ RESOURCE                        │ RESULT │ REASON    │
│────│─────────────────────│──────│─────────────────────────────────│────────│───────────│
│ 1  │ disallow-privileged │      │ v1/Pod/default/plain            │ Fail   │ Not found │
│ 2  │ disallow-privileged │      │ v1/Pod/default/privileged-false │ Fail   │ Not found │
│ 3  │ disallow-privileged │      │ v1/Pod/default/privileged-true  │ Fail   │ Not found │
│ 4  │ disallow-privileged │      │ v1/Pod/default/init-privileged  │ Fail   │ Not found │
│────│─────────────────────│──────│─────────────────────────────────│────────│───────────│


Test Summary: 0 tests passed and 4 tests failed

Error: 4 tests failed
exit code: 1

The apply command has two flags, --warn-exit-code and --warn-no-pass, whose help text says they raise a warning exit code “if no objects satisfied a policy”. I tried them against this broken policy on the shipped manifests. The exit code stayed 0, so I do not rely on them for this.

kyverno apply policies/ --resource manifests/ --warn-exit-code 3 --warn-no-pass; echo "exit code: $?"

Applying 3 policy rule(s) to 2 resource(s)...

pass: 4, fail: 0, warn: 0, error: 0, skip: 0 
exit code: 0

Audit mode is invisible to the tests

With validationActions: [Audit] in the latest-tag policy, kyverno apply still reports the bad Pod as failed and exits with 1, so an Audit policy fails a pull request in CI even though a cluster would only record the violation:

kyverno apply policies/disallow-latest-tag.yaml --resource examples/pod-bad.yaml; echo "exit code: $?"

Applying 1 policy rule(s) to 1 resource(s)...
policy disallow-latest-tag -> resource default/Pod/worker failed:
1 - validation Every image needs a tag other than latest, or a digest.

pass: 0, fail: 1, warn: 0, error: 0, skip: 0 
exit code: 1

The flag --audit-warn, described as “flag audit policies as warnings instead of failures”, changed nothing in my test: the output and the exit code were identical. The unit tests pass as before, so only a plain check on the policy files, like check 3 of the CI script, can see the setting.

A CEL error is not the same as a failure

Rewrite the limits expression without the optional chaining, as c.resources.limits.cpu != "". A Pod that sets no resources does not fail that rule; the expression cannot even be evaluated, because the field does not exist. In kyverno apply the damage is easy to miss:

kyverno apply policies/require-limits.yaml --resource manifests/pod-good.yaml --resource examples/pod-bad.yaml; echo "exit code: $?"

Applying 1 policy rule(s) to 2 resource(s)...

pass: 1, fail: 0, warn: 0, error: 1, skip: 0 
exit code: 1

The summary says error: 1 and the exit code is 1, but nothing says what went wrong. The flag --detailed-results only works together with --table:

kyverno apply policies/require-limits.yaml --resource examples/pod-bad.yaml --table --detailed-results; echo "exit code: $?"

Applying 1 policy rule(s) to 1 resource(s)...
│────│────────────────│──────│────────────────────│────────│────────│───────────────────────────────│
│ ID │ POLICY         │ RULE │ RESOURCE           │ RESULT │ REASON │ MESSAGE                       │
│────│────────────────│──────│────────────────────│────────│────────│───────────────────────────────│
│ 1  │ require-limits │      │ default/Pod/worker │ Error  │        │ error: no such key: resources │
│────│────────────────│──────│────────────────────│────────│────────│───────────────────────────────│
exit code: 1

In kyverno test the same mistake is plain. Every fixture that should be rejected reports the reason Want fail, got error:

kyverno test tests/require-limits; echo "exit code: $?"
│────│────────────────│────────────│────────────────────────────────────│────────│──────────────────────│
│ ID │ POLICY         │ RULE       │ RESOURCE                           │ RESULT │ REASON               │
│────│────────────────│────────────│────────────────────────────────────│────────│──────────────────────│
│ 1  │ require-limits │ validation │ v1/Pod/default/limits-ok           │ Pass   │ Ok                   │
│ 2  │ require-limits │ validation │ v1/Pod/default/limits-with-init    │ Pass   │ Ok                   │
│ 3  │ require-limits │ validation │ v1/Pod/default/no-resources        │ Fail   │ Want fail, got error │
│ 4  │ require-limits │ validation │ v1/Pod/default/cpu-only            │ Fail   │ Want fail, got error │
│ 5  │ require-limits │ validation │ v1/Pod/default/memory-only         │ Fail   │ Want fail, got error │
│ 6  │ require-limits │ validation │ v1/Pod/default/requests-only       │ Fail   │ Want fail, got error │
│ 7  │ require-limits │ validation │ v1/Pod/default/init-without-limits │ Fail   │ Want fail, got error │
│────│────────────────│────────────│────────────────────────────────────│────────│──────────────────────│


Test Summary: 2 tests passed and 5 tests failed

Error: 5 tests failed
exit code: 1

Two files for the same object crash kyverno apply

If two files in the folder you pass to --resource describe the same kind, name and namespace, as can happen when a folder holds both a base and an overlay, v1.20.0 panics instead of reporting. Copy manifests/deployment-good.yaml to manifests/deployment-copy.yaml and run the apply command from check 1:

kyverno apply policies/ --resource manifests/; echo "exit code: $?"
panic: deployments.apps "shop" already exists

goroutine 1 [running]:

The real output continues with a long Go stack trace, and the exit code is 2. Keep one file per object in the folder you give --resource, and delete the copy before you continue.

Confirm that everything works end to end

Three checks tell you the whole setup is sound. First, the CI script passes on the clean project, as in Step 10, with ci.sh: all checks passed and an exit code of 0. Second, the suite gives the same answer every time. Run it twenty times and count the distinct summary lines:

for i in $(seq 1 20); do kyverno test tests/ | grep "Test Summary"; done | sort | uniq -c; echo "exit code: $?"
     20 Test Summary: 26 tests passed and 0 tests failed
exit code: 0

One line with a count of 20 means every run printed the same total. If you see several different totals, look for CronJob fixtures, as described in Step 8. Third, every row of the mutants.py table shows at least one check that caught the mutant. If you change a policy later and one of those three signals changes, you have learned something before a cluster did.

Where to go next

You tested what the policy expressions decide. You did not test what a live cluster does with those decisions: whether the webhook is registered, how failures are handled, which namespaces are excluded. The Kyverno documentation’s comparison table names the tool for that layer: it lists “Kyverno CLI (unit), Chainsaw (e2e)” under testing. A real cluster, or a throwaway one, is the next step for that.

The Kyverno documentation also lists MutatingPolicy, GeneratingPolicy, DeletingPolicy and ImageValidatingPolicy next to ValidatingPolicy. I only tested ValidatingPolicy here, so read each type’s page before you copy this pattern. A ValidatingPolicy can also be applied to any JSON payload with spec.evaluation.mode: JSON, and the documentation shows a Terraform plan as the example, evaluated with the CLI. For a report your CI system can display, kyverno test accepts --output-format junit; in v1.20.0 the XML arrived on standard output between the progress lines and the summary, with nothing on standard error, so cut it out before you hand it to a reporting tool.

For background and neighbouring techniques on this site, see Kyverno Turns Kubernetes Policy From a Security Gate Into a Platform Primitive for background on where Kyverno fits, the audit of a CNCF guide’s seven Kyverno policies, which used this same offline approach to test a published demo, and the Open Policy Agent tutorial on guarding Terraform, which applies the same fixture-first thinking to a different policy language.

Sources and further reading

  • kyverno apply and kyverno test reference pages, Kyverno documentation (v1.20.0).
  • ValidatingPolicy, CEL libraries, Testing Policies and Migrating to CEL Policies, Kyverno documentation.
  • Kyverno v1.20.0 release with checksums, and kyverno/action-install-cli.
  • ValidatingAdmissionPolicy, Images, Resource management for Pods and containers and Pod Security Standards, Kubernetes documentation.
  • kyverno/policies, the community policy library whose test manifests use the format shown in Step 5.

Tags:

Admission ControlCELKubernetesKyvernoMutation TestingPolicy as Code

Share

Several small yellow spirit-level bubble vials on a camera tripod head and a base plate, each bubble resting near the center
Previous Post

DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
23 Nov
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
23 Nov
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
Trending
November 23, 2026
How to Test Kubernetes Admission Policies Without a Cluster: Write Kyverno ValidatingPolicies, Prove Them With kyverno test, and Gate Pull Requests in CI
November 23, 2026
DeepMind’s Quantum Agents Make Lean the Referee and the Headline Ratios Reproduce From the Released Files, but 260x of the Arcsin 290x Came From a Stage Classical Simulation Could Check, the 8x and 2.5x Use Refined Baselines, and the Fusion and Grover Figures Moved Between arXiv Versions
November 23, 2026
Norway’s National Security Authority Tells Every Azure API Management Customer to Assume Secrets Are Out, Microsoft’s Private Notice Limits Exposure to Classic Tiers That Skipped Its Guidance, and No CVE or Public Advisory Says What the Flaw Is
November 23, 2026
How to Stop pip From Installing a Typosquatted or Made-Up Package Name: Build a Name Gate in Python and Measure It on the 15,000 Most Downloaded PyPI Projects and 12,067 Names From OSSF’s Malicious-Package Reports
November 23, 2026
Dragos’s Canaries Turn AI-Router Privacy Flags Into a Measurement, and OpenRouter’s Public ZDR List Shows the Label Sat on the MiniMax and Phala Routes Through October, Its 125 Removals Reproduce as Eight Providers’ Entire Lists, and the Post Later Dropped Its Vercel and OpenRouter Example
November 23, 2026
Google Says a Suspected China-Nexus Group Exploited the vCenter Authentication Bypass in Early September, About Ten Weeks Before the Patch, but Broadcom’s Advisory Never Says It Was Exploited, the July Claim Rests on a Modifiable Build Timestamp, and the CVE Record Omits vCenter 7.0

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026