A wooden ship's wheel with a brass rim against a sunset sky and rigging, under the article title about writing Kyverno policies with an LLM
Cover based on a photo by Petty Officer 2nd Class LaNola Stone, U.S. Coast Guard, via Wikimedia Commons, Public domain

If you write Kyverno policies with an LLM, the first draft will usually be a ClusterPolicy. That's the policy type most Kyverno examples on the web use, so it's what models learned. It's also the type Kyverno is retiring. Kyverno 1.19 deprecated ClusterPolicy and Policy, and Kyverno 1.20 doesn't run them at all: the admission controller refuses to create them, and the 1.20 CLI won't load them. The replacement for validation is ValidatingPolicy, which uses CEL expressions instead of patterns. Models get that type wrong in quieter ways. In our lab, three of the broken drafts made kyverno apply print pass: 0, fail: 0 and exit 0, and one draft that looked fine would have blocked every ordinary Pod in the cluster. This guide shows the drafts, the exact output, and the checks that catch each one before a Kubernetes admission policy reaches a cluster.

We used the same rule as our OPA and Rego guide, "no privileged containers," so you can compare the two engines. That post covers Rego and opa test; this one only covers Kyverno.

What we ran, and what we didn't

Everything below ran on our lab box. Nothing touched a production cluster.

  • Kyverno CLI 1.19.1 and 1.20.0, the official Linux release builds from the Kyverno repository.
  • A single-node k3s cluster (Kubernetes 1.37) with Kyverno 1.20.0 installed from the release install.yaml. Kyverno 1.20 supports Kubernetes 1.34 to 1.37, per the 1.20 release announcement.
  • Five test resources: a Pod with a securityContext that doesn't set privileged, a Pod with no securityContext, a privileged Pod, a Pod whose only privileged container is an init container, and a Deployment with a privileged Pod template. On the cluster we only sent them as server-side dry runs, so nothing privileged ever started.

The drafts were written for this guide to reproduce mistakes models commonly make with Kyverno. They aren't a captured model transcript, and we didn't call a model in the lab. Model output is never the evidence here; the CLI and the API server are.

Why LLMs still write ClusterPolicy

Kyverno launched with ClusterPolicy: a list of rules, each with a match block and a validate, mutate, generate or verifyImages section, and YAML patterns like =(privileged): "false". Years of docs, blog posts and the public policy library used that format. Kyverno 1.14 started a new set of CEL-based types, and the Kyverno 1.19 announcement declared feature parity and deprecated the old ones:

Legacy rule typeReplacement in policies.kyverno.io
validate rulesValidatingPolicy
mutate rulesMutatingPolicy
generate rulesGeneratingPolicy
verifyImages rulesImageValidatingPolicy
CleanupPolicy / ClusterCleanupPolicyDeletingPolicy

Each type also has a namespaced variant, such as NamespacedValidatingPolicy. In 1.20, the release announcement says legacy policies "no longer execute in any Kyverno controller or in the CLI," existing ones show as not ready, and the legacy CRDs are planned for full removal in 1.21.

The new types also look a lot like Kubernetes' own ValidatingAdmissionPolicy. Kyverno's docs call a ValidatingPolicy "a superset of a ValidatingAdmissionPolicy." So a model has two older formats to blend into one draft: Kyverno's legacy fields and the Kubernetes field names.

How to write Kyverno policies with an LLM

The workflow has four steps: pin the version and policy type in the prompt, run the drafts through kyverno apply and read the errors, turn the expected results into a kyverno test suite, then check the policy on a lab cluster with server-side dry runs.

Diagram of the loop to write Kyverno policies with an LLM: the Kyverno version and policy type go into the prompt, the model drafts a ValidatingPolicy, kyverno test compares it against expected pass and fail resources, and only then does the policy go to a lab cluster for a server-side dry run; legacy ClusterPolicy, wrong apiVersion, unknown fields, Pod instead of pods and unsafe field access are each stopped before the cluster
Check the draft against passing and failing fixtures, then confirm admission with a server-side dry run. Image: RedRouter, Original

Step 1: Pin the Kyverno version and policy type in the prompt

Tell the model which Kyverno version you run and which kind you want. Without that, you'll get a ClusterPolicy. A prompt that worked as a starting point for us looks like this:

Kyverno version: 1.20. Write one ValidatingPolicy (apiVersion policies.kyverno.io/v1).
Do not use ClusterPolicy, Policy, match/any/resources/kinds, validationFailureAction or patterns.
Match with spec.matchConstraints.resourceRules using lowercase plural resource names.
Use CEL in spec.validations. Read optional fields with ?. and orValue().
Goal: deny Pods where any container, init container or ephemeral container sets
securityContext.privileged to true. Return only YAML.

Then check what your version actually accepts. kubectl explain works once the CRDs are installed, and the CEL migration guide recommends it:

kubectl explain vpol.spec
kyverno version

If you still run Kyverno 1.19, legacy policies work but print a deprecation warning. Don't ask a model for new ones.

Step 2: Run the LLM's drafts through kyverno apply

Here are six drafts and what each did, starting with the most common. All runs used kyverno apply <policy> -r <resource>... against the five test resources unless noted.

Draft 1: a legacy ClusterPolicy

This is the policy almost every model writes first:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-privileged-containers
spec:
  validationFailureAction: Enforce
  background: true
  rules:
  - name: privileged-containers
    match:
      any:
      - resources:
          kinds:
          - Pod
    validate:
      message: "Privileged mode is not allowed."
      pattern:
        spec:
          containers:
          - =(securityContext):
              =(privileged): "false"

On the 1.19.1 CLI it works, with a warning:

Warning: drafts/d1-clusterpolicy.yaml: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/
...
pass: 3, fail: 2, warn: 0, error: 0, skip: 0

It caught the privileged Pod and the Deployment but passed the Pod with a privileged init container, because the pattern only covers containers. On the 1.20.0 CLI it doesn't load:

Error: failed to load file drafts/d1-clusterpolicy.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. ...

And kubectl apply against the 1.20 cluster was denied by Kyverno's own webhook with the same message. If you're still on 1.19, add --warnings-as-errors to kyverno apply and kyverno test in CI. On 1.19.1 it turned the warning into a failure: Error: found 1 deprecation warning(s) and --warnings-as-errors is set, exit 1.

Draft 2: the new kind with an invented apiVersion

apiVersion: kyverno.io/v2
kind: ValidatingPolicy

The rest of the draft was correct. kyverno apply printed:

Applying 0 policy rule(s) to 5 resource(s)...

pass: 0, fail: 0, warn: 0, error: 0, skip: 0

Exit code 0. The CLI skipped the document and only said why at -v 3: failed to retrieve validator: kind ValidatingPolicy not found in kyverno.io/v2 groupversion. The cluster was clearer: no matches for kind "ValidatingPolicy" in version "kyverno.io/v2". The correct apiVersion is policies.kyverno.io/v1.

Draft 3: the new kind with legacy fields mixed in

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: disallow-privileged-containers
spec:
  validationFailureAction: Enforce
  match:
    any:
    - resources:
        kinds: [Pod]
  validations:
  - expression: "object.spec.containers.all(c, !c.?securityContext.?privileged.orValue(false))"
    message: "Privileged mode is not allowed."

Same result: 0 rules, pass: 0, fail: 0, exit 0. At -v 3 the CLI logged skipping invalid YAML file with spec.match: Invalid value: value provided for unknown field and the same for spec.validationFailureAction. The API server rejected it outright with strict decoding error: unknown field "spec.match", unknown field "spec.validationFailureAction".

Draft 4: Pod instead of pods

  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: [v1]
      operations: [CREATE, UPDATE]
      resources: [Pod]

This one is valid YAML for the schema, so the CLI loaded it: Applying 1 policy rule(s) to 5 resource(s), then pass: 0, fail: 0, exit 0. Nothing matched. resourceRules takes the lowercase plural resource name, pods, not the kind.

The cluster accepted it too. A server-side dry run of the privileged Pod returned pod/web-privileged created (server dry run). The only hint was the policy's status:

$ kubectl get validatingpolicy
NAME                             AGE   READY
disallow-privileged-containers   8s    false

The status message said missing permissions: get /v1, Resource=Pod. The capital P is the bug.

Draft 5: unsafe field access

  validations:
  - expression: "object.spec.containers.all(c, c.securityContext.privileged == false)"
    message: "Privileged mode is not allowed."

This is the draft that looks right. With table output, the CLI shows what it does:

│ 1  │ disallow-privileged-containers │      │ lab/Pod/web-ok                       │ Error  │        │ error: no such key: privileged      │
│ 2  │ disallow-privileged-containers │      │ lab/Pod/web-no-securitycontext       │ Error  │        │ error: no such key: securityContext │
│ 3  │ disallow-privileged-containers │      │ lab/Pod/web-privileged               │ Fail   │        │ Privileged mode is not allowed.     │
│ 4  │ disallow-privileged-containers │      │ lab/Pod/web-privileged-init          │ Error  │        │ error: no such key: securityContext │
│ 5  │ disallow-privileged-containers │      │ lab/Deployment/web-privileged-deploy │ Fail   │        │ Privileged mode is not allowed.     │

CEL doesn't treat a missing field as false. Reading c.securityContext.privileged on a container that doesn't set it is an error. On the cluster, the default summary line (fail: 2, error: 3) turned into an outage. The two harmless Pods were both denied:

Error from server: error when creating "res/pod-nosc.yaml": admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy disallow-privileged-containers error: error: no such key: securityContext

Most Pods don't set privileged at all, so this policy would have blocked nearly every new workload. Use CEL's optional syntax instead: c.?securityContext.?privileged.orValue(false). Kubernetes has supported CEL optional types since 1.29.

Draft 6: Audit instead of Deny

A model asked to "audit" privileged Pods, or one copying an example, may write validationActions: [Audit]. The CLI can't show the difference. kyverno apply reported the privileged Pod as fail with exit code 1, exactly as it did with Deny. The 1.20 CLI's help describes its --audit-warn flag as "Currently has no effect." On the cluster, the same Pod was admitted: pod/web-privileged created (server dry run). The validationActions values come from Kubernetes' ValidatingAdmissionPolicy: Audit records the failure without blocking the request, and only Deny blocks it. Check validationActions by eye or with a grep; don't rely on apply for it.

Step 3: Turn exit code 0 into a real test with kyverno test

Three of the six drafts passed kyverno apply with exit code 0, and draft 6 passed with the result you'd expect from a correct policy. kyverno apply tells you what the policy did to the resources you gave it. It doesn't tell you whether that's what you wanted.

Two flags help. --warn-no-pass --warn-exit-code 3 made drafts 2, 3 and 4 exit 3 with exit as no objects satisfied policy. The better fix is a test file that states the expected result for every resource. This is the format the Kyverno repository uses for ValidatingPolicy tests:

apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: disallow-privileged-containers
policies:
- policy.yaml
resources:
- resources.yaml
results:
- isValidatingPolicy: true
  policy: disallow-privileged-containers
  kind: Pod
  resources:
  - web-ok
  - web-no-securitycontext
  result: pass
- isValidatingPolicy: true
  policy: disallow-privileged-containers
  kind: Pod
  resources:
  - web-privileged
  - web-privileged-init
  result: fail
- isValidatingPolicy: true
  policy: disallow-privileged-containers
  kind: Deployment
  resources:
  - web-privileged-deploy
  result: fail

With each broken draft saved as policy.yaml, kyverno test failed every time:

  • Draft 2 and draft 4: all five rows Fail with reason Not found, Error: 5 tests failed.
  • Draft 3: Error: failed to run test with both unknown fields named.
  • Draft 5: Want pass, got error for the two harmless Pods and Want fail, got error for the init-container Pod, Error: 3 tests failed.

That's the gate to put between the model and your repository. Include at least one resource that must pass. Without it, you won't catch a policy that denies everything. The testing guide shows how to run the same command in CI.

Step 4: Check the policy on a lab cluster

A clean kyverno test run isn't the last step. The cluster runs the policy through a webhook, with RBAC, autogen and a failurePolicy the CLI doesn't model. In a lab cluster, apply the policy, wait for it to report ready, and send dry runs:

kubectl apply -f policy.yaml
kubectl get validatingpolicy          # READY must be true
kubectl apply --dry-run=server -f res/pod-priv.yaml
kubectl apply --dry-run=server -f res/pod-nosc.yaml

A server-side dry run goes through admission webhooks, so it shows what a real create would do without creating anything. READY false is worth reading: for draft 4, it was the only sign the policy didn't match anything.

The fixed ValidatingPolicy

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

kyverno test passed all five rows on both the 1.19.1 and 1.20.0 CLI. On the 1.20 cluster, the policy reported READY true, the two harmless Pods were admitted, and the other three were denied with the container named:

Error from server: error when creating "res/pod-priv-init.yaml": admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy disallow-privileged-containers failed: privileged containers are not allowed: setup

The Deployment was denied too, even though the policy only matches pods. Kyverno generated controller variants automatically. The policy's status listed autogenerated versions for DaemonSets, Deployments, ReplicaSets, StatefulSets, Jobs and CronJobs, with the allContainers variable rewritten to object.spec.template.spec... (and object.spec.jobTemplate.spec.template.spec... for CronJobs). That's why the variable matters: it gets rewritten once, and every validation uses it. If you want to control which controllers get variants, the ValidatingPolicy docs cover spec.autogen.podControllers.

The messageExpression names the offending container. If it fails to evaluate, Kyverno falls back to message, so add a static message too if you want a guaranteed fallback.

Automate the loop: draft, test, fix

The model drafts a policy, kyverno test judges it, and the exact output goes back to the model. The drafting side calls RedRouter's OpenAI-compatible endpoint (base URL https://redrouter.org/v1 with a Bearer key, per the RedRouter quickstart). We didn't call a model in the lab, so treat this as a sketch:

import os, pathlib, subprocess
from openai import OpenAI

client = OpenAI(base_url="https://redrouter.org/v1",
                api_key=os.environ["REDROUTER_API_KEY"])

SUITE = pathlib.Path("tests/disallow-privileged")   # kyverno-test.yaml + resources.yaml
SYSTEM = ("Kyverno 1.20. Write one ValidatingPolicy, apiVersion policies.kyverno.io/v1. "
          "No ClusterPolicy, no match/kinds, no validationFailureAction, no patterns. "
          "Lowercase plural resources. Read optional fields with ?. and orValue(). "
          "validationActions: [Deny]. Return only YAML.")
GOAL = ("Deny Pods where any container, init container or ephemeral container "
        "sets securityContext.privileged to true. Policy name: disallow-privileged-containers.")

def draft(feedback=""):
    r = client.chat.completions.create(
        model="glm-5.3-flash-red", temperature=0,
        messages=[{"role": "system", "content": SYSTEM},
                  {"role": "user", "content": f"{GOAL}\n\n{feedback}"}])
    return r.choices[0].message.content.strip().removeprefix("```yaml").strip("`\n")

policy = draft()
for _ in range(4):
    (SUITE / "policy.yaml").write_text(policy)
    run = subprocess.run(["kyverno", "test", str(SUITE.parent), "--remove-color"],
                         capture_output=True, text=True)
    if run.returncode == 0 and "Deny" in policy:
        break
    policy = draft(f"Your policy:\n{policy}\n\nkyverno test printed:\n{run.stdout}{run.stderr}\nFix it.")
print(policy)

The model never sees the test file, so it can't edit the expectations to match its policy. The loop also checks for Deny itself, because kyverno test can't tell Deny from Audit. A passing result still goes to a lab cluster and a human review before it's merged.

What to send the model

Admission policies are low-risk to share. The manifests you test them against may not be. Real Deployments and Pod specs can carry internal registry names, environment variables, mounted secret names and sometimes credentials pasted into env.

  • Send the goal, the Kyverno version and the policy type. That's enough to draft the policy.
  • Send the exact kyverno test or kubectl error back, not a paraphrase.
  • Write small synthetic test resources like the five above instead of exporting live objects. If you do use a real manifest, strip env, image registry hosts and annotations first.
  • Note that kyverno apply --explain prints the values expressions read, and its help warns that a policy reading a Secret will print that Secret's data. Don't paste that output into a prompt.

On RedRouter, Zero Data Retention is an opt-in setting and off by default. The data handling docs explain what's stored and how to turn it on, and what RedRouter keeps is the short version. Our security page covers how we handle security workloads.

Which model to use for Kyverno policies

For drafting Kyverno policies, we'd start with GLM 5.3 Flash Red (glm-5.3-flash-red). On docs.redrouter.org/models it lists at $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. The system prompt and the goal repeat on every loop iteration, and a policy is short. For admission policy work inside a broader authorized red-team or cluster assessment, red-cyber-1 (Beta) lists at $0.28 / $0.13 / $1.10 per 1M. Plans are on /pricing.

Common LLM mistakes in Kyverno policies

Mistake in the draftWhat we sawFix
kyverno.io/v1 ClusterPolicy1.19.1: works with a deprecation warning. 1.20: CLI won't load it, webhook denies itWrite a ValidatingPolicy in policies.kyverno.io/v1
Invented apiVersion (kyverno.io/v2)CLI: 0 rules, exit 0, reason only at -v 3. Cluster: no matches for kindpolicies.kyverno.io/v1
match/kinds or validationFailureAction in a ValidatingPolicyCLI: 0 rules, exit 0. Cluster: strict decoding error: unknown fieldmatchConstraints.resourceRules, validationActions
resources: [Pod]CLI: nothing matched, exit 0. Cluster: accepted, READY false, privileged Pod admittedresources: [pods]
c.securityContext.privilegedno such key errors; every Pod without the field deniedc.?securityContext.?privileged.orValue(false)
Checks only containersPrivileged init container passesJoin containers, initContainers, ephemeralContainers
validationActions: [Audit]CLI reports fail as with Deny; cluster admits the Pod[Deny], checked by eye or grep

Validation checklist

  • The kind is a policies.kyverno.io/v1 type, not ClusterPolicy or Policy, and the CLI version in CI matches the cluster.
  • kubectl explain vpol.spec (or the API reference) lists every field in the draft.
  • resourceRules uses lowercase plural resource names and the right apiGroups.
  • Every optional field is read with ?. and orValue(), and init and ephemeral containers are covered.
  • validationActions is [Deny] if the policy should block.
  • kyverno test passes with at least one expected pass and one expected fail resource.
  • On a lab cluster, READY is true and server-side dry runs give the expected allow and deny.
  • Test resources are synthetic or scrubbed, and the policy is only applied to clusters you own or are authorized to change.

FAQ

Can an LLM write Kyverno policies that work the first time?

Sometimes, if you tell it the version and the policy type. Without that, expect a ClusterPolicy, which Kyverno 1.20 won't run. In our lab, the broken drafts that failed quietly were more of a problem than the ones that failed loudly. Put kyverno test with expected results between the model and the cluster.

Should an LLM still write a Kyverno ClusterPolicy?

No, not for new policies. ClusterPolicy and Policy were deprecated in Kyverno 1.19, and 1.20 doesn't execute them or accept new ones. If you have existing ones, a model can help convert them, but check each conversion against the field mapping in the CEL migration guide and run the same tests before and after.

Is a Kyverno ValidatingPolicy the same as a Kubernetes ValidatingAdmissionPolicy?

No. A ValidatingPolicy uses the same matchConstraints, validations and validationActions fields, and Kyverno can generate a ValidatingAdmissionPolicy from one. It adds Kyverno features such as background scans, exceptions, reports, autogen for Pod controllers and CLI testing. A model that knows ValidatingAdmissionPolicy will get the shape mostly right, but check the apiVersion and kind.

How is AI for Kubernetes admission policy with Kyverno different from OPA?

The checks are the same idea: draft, test, then dry-run. The engines differ. Kyverno policies are Kubernetes resources with CEL expressions, tested with kyverno test. OPA policies are Rego, usually run through Gatekeeper, and tested with opa test. Our OPA and Rego guide covers that side. For runtime detection after a Pod starts, see Falco rules with an LLM; admission policy only decides what gets created.

Related guides

Only apply admission policies to clusters you own or are authorized to change, and test them in a lab cluster before they reach shared environments.