Containers

OPA Gatekeeper vs Kyverno: Kubernetes Policy Examples Tested

You want one rule enforced on every cluster: pods only pull from registries you trust, every pod carries an owner label, and unsigned images never start. OPA Gatekeeper and Kyverno both promise that, and most comparisons stop at “Rego versus YAML”. That framing is now out of date, because Kyverno moved its policy language to CEL and stopped accepting the old ClusterPolicy kind altogether, while Gatekeeper now takes CEL templates next to Rego.

Original content from computingforgeeks.com - post 167279

So we installed both engines on the same cluster, wrote matching policies for each, and pushed the same bad manifests through them. This post shows the exact deny message each engine returns, how audit and background scans report old violations, what mutation and image verification look like when they really run, and the admission latency and memory we measured. We built the lab on a single kubeadm node on GCP in November 2026, with Kubernetes 1.37.3, Gatekeeper 3.23.1 and Kyverno 1.20.0, and every output below is pasted from that box.

The verdict: OPA Gatekeeper vs Kyverno

Pick Kyverno if you need built-in image signature verification, user-aware mutation without extra services, or policies that block a bad Deployment before it exists. Pick Gatekeeper if your team already writes Rego, you share policies with OPA outside Kubernetes, or you want the lighter webhook that fails open by default. Both blocked every bad manifest we threw at them, so the choice is about workflow and failure behaviour, not coverage.

The table sums up what the lab showed. Every row comes from a command we ran, and the sections that follow show the output behind each one, so you can check any cell against the raw result before you trust it for your own cluster.

What we testedOPA GatekeeperKyverno
Policy languageRego in a ConstraintTemplate (v0 in rego:, v1 under code:), or CELCEL in ValidatingPolicy and friends; legacy ClusterPolicy refused
Bad image in a DeploymentDeployment created, ReplicaSet stuck on FailedCreateDeployment denied at apply time
MutationAssignMetadata; requesting user only through an external data providerMutatingPolicy reads the requesting user natively
Image signature checkNot built in (needs Ratify or external data)ImageValidatingPolicy with cosign, rewrites tag to digest
Existing violationsConstraint status, totalViolationsPolicyReport objects per resource
Webhook failure policyIgnore, 3 s timeout (fails open)Fail, 10 s timeout (fails closed)
Admission time per podAbout 5.1 ms (mutation plus validation)About 7.8 ms for one mutate and two validate policies
Pods and memory2 pods, about 163 MiB working set4 pods, about 180 MiB working set
Helm install with --wait32.6 s50.6 s

Admission control sits on top of the built-in controls, not instead of them. If you have not set up Pod Security Standards from baseline to restricted and tight RBAC roles and ServiceAccounts yet, do that first. Policy engines cover what those two cannot express, such as registry allowlists, label conventions and supply chain checks.

Step 1: Install Gatekeeper and Kyverno on the same cluster

Both engines install side by side with Helm: Gatekeeper settled in 32.6 s with 2 pods, Kyverno in 50.6 s with 4. They coexist because each one only enforces in the namespaces its policies match. We used a single node built with kubeadm on Ubuntu, Calico for networking and metrics-server for the footprint numbers. A lab like this needs about 4 vCPU and 8 GB of RAM; production clusters run three Kyverno admission replicas and at least two Gatekeeper controller replicas, so plan memory for that.

Add the two Helm repositories first. Both projects publish their charts from their own GitHub Pages sites, so there is no shared repository to worry about.

helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm repo add kyverno https://kyverno.github.io/kyverno/
helm repo update

We pinned both chart versions so the results are repeatable, and kept one replica per component because this is a single node. Gatekeeper went in first:

# https://github.com/open-policy-agent/gatekeeper/releases
time helm install gatekeeper gatekeeper/gatekeeper --version 3.23.1 -n gatekeeper-system --create-namespace --set replicas=1 --set audit.replicas=1 --wait

Our audit.replicas flag turned out to be a no-op: the Gatekeeper audit controller always runs as a single pod, so you can drop that flag. Kyverno ships four controllers, so its install takes longer to settle. The chart version maps to an app version, and chart 3.10.0 carries Kyverno v1.20.0:

# https://github.com/kyverno/kyverno/releases
time helm install kyverno kyverno/kyverno --version 3.10.0 -n kyverno --create-namespace --set admissionController.replicas=1 --set backgroundController.replicas=1 --set cleanupController.replicas=1 --set reportsController.replicas=1 --wait --timeout 10m

Gatekeeper reported ready in 32.6 seconds and Kyverno in 50.6 seconds. The Kyverno chart notes are worth reading this time, because they already warn you about the change that breaks most older tutorials:

⚠️  WARNING: The legacy kyverno.io policy types are deprecated and will be removed in a future release. Migrate to their policies.kyverno.io replacements:
    - ClusterPolicy / Policy → ValidatingPolicy, MutatingPolicy, GeneratingPolicy, ImageValidatingPolicy (and their namespaced variants)
    - ClusterCleanupPolicy / CleanupPolicy → DeletingPolicy / NamespacedDeletingPolicy
    - PolicyException (kyverno.io) → PolicyException (policies.kyverno.io)
    See https://kyverno.io/docs/guides/migration-to-cel/ for the migration guide.

Before you write any policy, check that both releases deployed and every pod is running. A policy applied while the Kyverno admission controller is still starting simply waits, which makes the first test look broken when it is not.

helm list -A
kubectl get pods -n gatekeeper-system
kubectl get pods -n kyverno

Gatekeeper runs two pods (the webhook controller and the audit controller) while Kyverno runs four: admission, background, cleanup and reports. That split matters later, because each extra Kyverno controller is another deployment you need to size and monitor.

Gatekeeper and Kyverno Helm releases and pods running side by side on a kubeadm Kubernetes node

To compare them fairly we gave each engine its own namespaces, so you can tell at a glance which engine produced which result. Create them, and start an nginx:1.27 pod in each legacy namespace before any policy exists:

kubectl create ns legacy-gk
kubectl create ns legacy-kv
kubectl run legacy-nginx --image=nginx:1.27 -n legacy-gk
kubectl run legacy-nginx --image=nginx:1.27 -n legacy-kv
kubectl create ns nopolicy
kubectl create ns policy-test
kubectl create ns policy-test-kv
kubectl create ns verify-kv

Each namespace has one job in the tests that follow:

  • policy-test for Gatekeeper policies
  • policy-test-kv for Kyverno policies
  • nopolicy as the latency control
  • legacy-gk and legacy-kv, each with an nginx:1.27 pod started before any policy
  • verify-kv for the image signature test

Those legacy pods are what the audit section reports on later. If you reproduce this on a shared cluster, use the same split so a policy you are testing never touches real workloads.

Step 2: Write the same registry allowlist for both engines

Gatekeeper needs a ConstraintTemplate plus a Constraint, Kyverno needs one CEL ValidatingPolicy, and both blocked nginx:1.27. The policy allows images only from ghcr.io/ and registry.k8s.io/. In Gatekeeper this takes two objects: a ConstraintTemplate that holds the Rego and creates a new CRD, and a Constraint that uses that CRD with parameters. The template below is the gatekeeper-library k8sallowedrepos logic. Save it as gk-allowedrepos-template-v0.yaml:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
  annotations:
    description: Requires container images to begin with a string from the specified list.
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
      validation:
        openAPIV3Schema:
          type: object
          properties:
            repos:
              description: The list of prefixes a container image is allowed to have.
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sallowedrepos

        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          satisfied := [good | repo = input.parameters.repos[_]; good = startswith(container.image, repo)]
          not any(satisfied)
          msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos])
        }

        violation[{"msg": msg}] {
          container := input.review.object.spec.initContainers[_]
          satisfied := [good | repo = input.parameters.repos[_]; good = startswith(container.image, repo)]
          not any(satisfied)
          msg := sprintf("initContainer <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos])
        }

The rego: field only takes the older v0 style shown above. We put the newer import rego.v1 form and the contains ... if syntax into that field, and Gatekeeper refused both at ingest time; the exact errors are in the troubleshooting section. Rego v1 works only under targets[].code[] with engine: Rego and source.version: "v1", and Gatekeeper also accepts CEL templates through its K8sNativeValidation engine, so CEL is not a Kyverno-only option. The Constraint then scopes the rule to Pods in our two Gatekeeper namespaces. Save it as gk-allowedrepos-constraint.yaml:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
  name: only-trusted-registries
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    namespaces: ["policy-test", "legacy-gk"]
  parameters:
    repos:
      - "ghcr.io/"
      - "registry.k8s.io/"

Apply the template first. Give Gatekeeper a few seconds to register the new K8sAllowedRepos kind, then apply the constraint and check its status.

kubectl apply -f gk-allowedrepos-template-v0.yaml
sleep 8; kubectl get constrainttemplate k8sallowedrepos -o jsonpath="{.status}{\"\n\"}"
kubectl apply -f gk-allowedrepos-constraint.yaml
sleep 5; kubectl get k8sallowedrepos only-trusted-registries

The violation count is already 1 a few seconds later. That is the legacy nginx pod in legacy-gk, found by the audit controller without any extra setup, so you get a list of existing offenders the moment a constraint lands.

NAME                      ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
only-trusted-registries   deny                 1

That gives Gatekeeper a working allowlist. Kyverno is where the old examples break.

The Kyverno ClusterPolicy you copied from an older guide no longer applies

Kyverno 1.20 refuses a kyverno.io/v1 ClusterPolicy outright, so the old examples must be rewritten as CEL. Most Kyverno examples online, including the earlier version of this post, use kind: ClusterPolicy with validationFailureAction: Enforce and a wildcard pattern. We applied exactly that file to see what happens on the current release. Kyverno printed a deprecation warning and then refused the object outright:

Error from server: error when creating "kv-trusted-registries-deprecated.yaml": admission webhook "validate-policy.kyverno.svc" denied the request: 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/

This matters for anyone upgrading. Existing ClusterPolicy objects stay readable, but Kyverno no longer runs them, so a cluster upgraded with old policies in place has no enforcement from them until you migrate. The Kyverno migration guide to CEL policies maps every old kind to its replacement. The replacement for our rule is a ValidatingPolicy written in CEL, the same expression language Kubernetes uses for ValidatingAdmissionPolicy. Save it as kv-trusted-registries.yaml:

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: only-trusted-registries
spec:
  validationActions: [Deny]
  evaluation:
    background:
      enabled: true
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: In
          values: ["policy-test-kv", "legacy-kv"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: >-
        object.spec.containers.all(c,
          c.image.startsWith('ghcr.io/') || c.image.startsWith('registry.k8s.io/'))
      messageExpression: >-
        'container image must come from ghcr.io/ or registry.k8s.io/, got: ' +
        object.spec.containers.map(c, c.image).join(', ')

Apply it and confirm Kyverno marks it ready. The READY column only turns true once the webhook for this policy is registered, so a false value means requests are not being checked yet.

kubectl apply -f kv-trusted-registries.yaml
kubectl get validatingpolicy only-trusted-registries

The screenshot below shows both halves of that run: the legacy ClusterPolicy refused, then the CEL version created and ready ten seconds later.

Kyverno 1.20 rejecting a legacy kyverno.io ClusterPolicy and accepting the same rule as a ValidatingPolicy

One gap to close before production: the Gatekeeper template also checks initContainers, while this CEL expression only checks spec.containers, so if you copy it, add a second validation with the expression object.spec.?initContainers.orValue([]).all(c, c.image.startsWith('ghcr.io/') || c.image.startsWith('registry.k8s.io/')). Notice also that the Kyverno version is one file where Gatekeeper needs two. That is still true with CEL, and it is the main reason teams new to policy engines find Kyverno quicker to start with.

Step 3: Compare the deny messages for the same bad pod

Both engines block the pod: Gatekeeper names the constraint, container and allowed repos, while Kyverno names the policy and the offending image. That message is what lands in CI logs. We pushed one manifest into each namespace, a Pod with a single nginx:1.27 container. Save it as bad-registry-pod.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: bad-registry
  labels:
    owner: lab
spec:
  containers:
    - name: web
      image: nginx:1.27

It carries the owner label so that only the registry rule can reject it. Apply it to both policy namespaces:

kubectl apply -f bad-registry-pod.yaml -n policy-test
kubectl apply -f bad-registry-pod.yaml -n policy-test-kv

Gatekeeper answers with HTTP 403 Forbidden and prefixes the message with the constraint name in brackets. Everything after the brackets is the msg string from the Rego, so the template author controls the wording.

Error from server (Forbidden): error when creating "bad-registry-pod.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [only-trusted-registries] container <web> has an invalid image repo <nginx:1.27>, allowed repos are ["ghcr.io/", "registry.k8s.io/"]

Kyverno names the policy in the sentence itself and returns whatever your messageExpression builds. The webhook name also tells you the policy type, vpol for a ValidatingPolicy, which helps when several policies match the same request.

Error from server: error when creating "bad-registry-pod.yaml": admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy only-trusted-registries failed: container image must come from ghcr.io/ or registry.k8s.io/, got: nginx:1.27

Here are both side by side in one terminal, with a compliant pod admitted by both for contrast. That one is good-pod.yaml: the same manifest renamed good-pod, with a pause container on registry.k8s.io/pause:3.10. Same manifest, same intent, and two quite different strings for your developers to read.

Gatekeeper and Kyverno admission deny messages for the same nginx pod manifest

If your pipeline greps for Forbidden to decide whether a deploy failed on policy, you will miss every Kyverno denial, because only the Gatekeeper error carries that word. A safer test is the string denied the request, which both engines print, so one grep covers either engine and survives a later switch.

Step 4: Push a bad Deployment and watch where it stops

Kyverno denies the Deployment at apply time; Gatekeeper admits it and the ReplicaSet then fails with FailedCreate. This is the difference that surprised us most. Real workloads arrive as Deployments, not bare pods, and the two engines handle that very differently with Pod-only policies. Save this one replica Deployment as bad-deploy.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: bad-deploy
  labels:
    owner: lab
spec:
  replicas: 1
  selector:
    matchLabels:
      app: bad-deploy
  template:
    metadata:
      labels:
        app: bad-deploy
        owner: lab
    spec:
      containers:
        - name: web
          image: nginx:1.27

Then apply the same file to each namespace:

kubectl apply -f bad-deploy.yaml -n policy-test
kubectl apply -f bad-deploy.yaml -n policy-test-kv

Gatekeeper let the Deployment through, because the constraint only matches Pods. Kyverno denied the Deployment itself, since a ValidatingPolicy on pods auto-generates matching rules for Deployments, ReplicaSets, StatefulSets, DaemonSets, Jobs and CronJobs:

deployment.apps/bad-deploy created
Error from server: error when creating "bad-deploy.yaml": admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy only-trusted-registries failed: container image must come from ghcr.io/ or registry.k8s.io/, got: nginx:1.27

In the Gatekeeper namespace, the Deployment exists but never gets a pod. The ReplicaSet keeps trying, and Gatekeeper keeps rejecting each pod it creates:

kubectl get deploy,rs -n policy-test
kubectl get events -n policy-test --field-selector reason=FailedCreate

Twelve failed pod creations in fifteen seconds, with the deny message buried in an event. Nothing in the apply output hinted at it.

NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/bad-deploy   0/1     0            0           15s

NAME                                  DESIRED   CURRENT   READY   AGE
replicaset.apps/bad-deploy-87bbc8bc   1         0         0       15s
LAST SEEN   TYPE      REASON         OBJECT                           MESSAGE
5s          Warning   FailedCreate   replicaset/bad-deploy-87bbc8bc   Error creating: admission webhook "validation.gatekeeper.sh" denied the request: [only-trusted-registries] container <web> has an invalid image repo <nginx:1.27>, allowed repos are ["ghcr.io/", "registry.k8s.io/"]

The terminal capture below has both namespaces after fifteen seconds, plus the describe rs output with ReplicaFailure set to FailedCreate. Look at the Kyverno namespace: there is no Deployment at all, because it never got past admission.

Gatekeeper admits a Deployment whose ReplicaSet then fails with FailedCreate while Kyverno denies the Deployment directly

For a developer running kubectl apply or a GitOps controller syncing a repo, the Gatekeeper behaviour looks like success at first. The apply returns zero and the failure only shows up later as a Deployment that never becomes ready, which is exactly the kind of silent stall that a canary rollout with automatic rollback exists to catch. To get the Kyverno behaviour from Gatekeeper, add the workload kinds to the constraint’s match.kinds and teach the Rego to read spec.template.spec.containers, or create an ExpansionTemplate that applies pod constraints to the spec.template of Deployments.

Step 5: Require an owner label on every pod

Both engines reject a pod with no owner label, and only the Gatekeeper message lists the missing keys. The policy is the classic required-labels check. For Gatekeeper we used the gatekeeper-library k8srequiredlabels template, again in v0 Rego. Save it as gk-requiredlabels-template.yaml:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
  annotations:
    description: Requires resources to contain specified labels.
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          type: object
          properties:
            message:
              type: string
            labels:
              type: array
              description: A list of labels the object must specify.
              items:
                type: object
                properties:
                  key:
                    type: string
                    description: The required label.
                  allowedRegex:
                    type: string
                    description: If specified, a regular expression the annotation's value must match.
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels

        get_message(parameters, _default) = _default {
          not parameters.message
        }

        get_message(parameters, _) = parameters.message {
          parameters.message
        }

        violation[{"msg": msg, "details": {"missing_labels": missing}}] {
          provided := {label | input.review.object.metadata.labels[label]}
          required := {label | label := input.parameters.labels[_].key}
          missing := required - provided
          count(missing) > 0
          def_msg := sprintf("you must provide labels: %v", [missing])
          msg := get_message(input.parameters, def_msg)
        }

The constraint asks for the owner key on Pods in policy-test. Save it as gk-requiredlabels-constraint.yaml.

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: pods-must-have-owner
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    namespaces: ["policy-test"]
  parameters:
    labels:
      - key: owner

The Kyverno version is a single CEL expression in one object, with no separate template to keep in sync. Save it as kv-require-labels.yaml.

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: require-labels
spec:
  validationActions: [Deny]
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: In
          values: ["policy-test-kv"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: "has(object.metadata.labels) && 'owner' in object.metadata.labels"
      message: "label 'owner' is required"

Our test pod is a pause container with no labels at all. Save it as unlabelled-pod.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: unlabelled
spec:
  containers:
    - name: pause
      image: registry.k8s.io/pause:3.10

Apply the three policies, with a twenty second pause after the template, then send the test pod. The pause matters because Gatekeeper creates the K8sRequiredLabels CRD from the template a few seconds after you apply it, and a Constraint applied before that CRD exists fails with a no matches for kind error. In a GitOps repo, put templates in an earlier sync wave than constraints, which either tool in our Flux CD vs ArgoCD comparison supports:

kubectl apply -f gk-requiredlabels-template.yaml
sleep 20
kubectl apply -f gk-requiredlabels-constraint.yaml
kubectl apply -f kv-require-labels.yaml
sleep 10
kubectl get validatingpolicy
kubectl apply -f unlabelled-pod.yaml -n policy-test
kubectl apply -f unlabelled-pod.yaml -n policy-test-kv

Both reject it. Gatekeeper prints the missing set computed by the Rego, and Kyverno prints the static message from the policy, so only Gatekeeper tells you which keys were missing when several are required.

Error from server (Forbidden): error when creating "unlabelled-pod.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [pods-must-have-owner] you must provide labels: {"owner"}
Error from server: error when creating "unlabelled-pod.yaml": admission webhook "vpol.validate.kyverno.svc-fail-8edb4697" denied the request: Policy require-labels failed: label 'owner' is required

The Kyverno webhook name now has a hash suffix. In our lab Kyverno added a suffixed webhook once a second policy with a different match arrived, and those extra webhooks are why its latency adds up per policy in Step 9.

Step 6: Mutate pods with AssignMetadata and MutatingPolicy

Kyverno set the owner label from the requesting user; Gatekeeper could only write a static default. Mutation is where the engines stop being equivalent. The Gatekeeper mutation webhook is on by default in current charts, and you can confirm it from the controller arguments, which include --operation=mutation-webhook. We added two AssignMetadata objects for team and managed-by, one object per label, because each AssignMetadata writes exactly one location. Here is the team one, saved as gk-assign-team.yaml.

apiVersion: mutations.gatekeeper.sh/v1
kind: AssignMetadata
metadata:
  name: add-team-label
spec:
  match:
    scope: Namespaced
    kinds:
      - apiGroups: ["*"]
        kinds: ["Pod"]
    namespaces: ["policy-test"]
  location: "metadata.labels.team"
  parameters:
    assign:
      value: "platform"

The second object differs only in its name, location and value. Save it as gk-assign-managed-by.yaml:

apiVersion: mutations.gatekeeper.sh/v1
kind: AssignMetadata
metadata:
  name: add-managed-by-label
spec:
  match:
    scope: Namespaced
    kinds:
      - apiGroups: ["*"]
        kinds: ["Pod"]
    namespaces: ["policy-test"]
  location: "metadata.labels.managed-by"
  parameters:
    assign:
      value: "gatekeeper"

On the Kyverno side a single MutatingPolicy sets all three labels in one CEL apply configuration, and the owner label comes from the user who sent the request. AssignMetadata can only reach the username through an external data provider that you deploy and register yourself. Save it as kv-add-team-labels.yaml.

apiVersion: policies.kyverno.io/v1
kind: MutatingPolicy
metadata:
  name: add-team-labels
spec:
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: In
          values: ["policy-test-kv"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
  mutations:
    - patchType: ApplyConfiguration
      applyConfiguration:
        expression: >-
          Object{
            metadata: Object.metadata{
              labels: {
                "team": "platform",
                "managed-by": "kyverno",
                "owner": request.userInfo.username
              }
            }
          }

Apply the three mutators, give them fifteen seconds to register, then send the unlabelled pod from Step 5 to both namespaces again:

kubectl apply -f gk-assign-team.yaml
kubectl apply -f gk-assign-managed-by.yaml
kubectl apply -f kv-add-team-labels.yaml
sleep 15; kubectl get assignmetadata,mutatingpolicy
kubectl apply -f unlabelled-pod.yaml -n policy-test
kubectl apply -f unlabelled-pod.yaml -n policy-test-kv

Gatekeeper still denied it with the same pods-must-have-owner message, because AssignMetadata added team and managed-by but nothing set owner. Kyverno admitted it, since mutation runs before validation and filled the owner from the request. Read the labels back:

kubectl get pod unlabelled -n policy-test-kv -o jsonpath="{.metadata.labels}{\"\n\"}"

The owner is the kubeadm admin identity that ran kubectl, which is the audit trail you actually want. A CI service account would show up here as system:serviceaccount:....

{"managed-by":"kyverno","owner":"kubernetes-admin","team":"platform"}

Gatekeeper can fill the requesting user in AssignMetadata only through externalData with dataSource: Username, which needs an external data provider running in the cluster. Without one, the closest you get is a static default. We added a third object, gk-assign-owner-default.yaml, that assigns owner: unassigned:

apiVersion: mutations.gatekeeper.sh/v1
kind: AssignMetadata
metadata:
  name: add-owner-label-default
spec:
  match:
    scope: Namespaced
    kinds:
      - apiGroups: ["*"]
        kinds: ["Pod"]
    namespaces: ["policy-test"]
  location: "metadata.labels.owner"
  parameters:
    assign:
      value: "unassigned"

Apply it, wait a few seconds and send the pod to policy-test once more:

kubectl apply -f gk-assign-owner-default.yaml
sleep 8; kubectl apply -f unlabelled-pod.yaml -n policy-test
kubectl get pod unlabelled -n policy-test -o jsonpath="{.metadata.labels}{\"\n\"}"

This time the pod went through in policy-test too, and these are the labels Gatekeeper wrote:

{"managed-by":"gatekeeper","owner":"unassigned","team":"platform"}

Look at what just happened to the required-labels policy, though. A default owner of unassigned satisfies it, so the mutation quietly defeats the validation you wrote in Step 5. The Kyverno side has the same problem, because the MutatingPolicy writes owner on every pod it matches and require-labels can no longer fail there either. Pick one: enforce the label or default it, never both on the same key. If you need both, default a different key such as owner-default and keep your validation strict.

Labels added by Gatekeeper AssignMetadata and Kyverno MutatingPolicy on an unlabelled pod

One more difference shows up in failure handling. The Gatekeeper mutating webhook is registered with failurePolicy: Ignore and a 1 second timeout, so if the controller is down, pods are admitted without the labels. The Kyverno mpol webhook uses Fail with 10 seconds, so pods wait or fail instead. If anything downstream depends on those labels, such as cost reports or network policy selectors, you want to know which of the two you are running.

Step 7: Verify cosign image signatures with Kyverno

Kyverno blocked the unsigned image and pinned the signed one to its digest; Gatekeeper has nothing built in for this. Signature verification is the clearest functional gap. Kyverno has a dedicated ImageValidatingPolicy kind; Gatekeeper has no built-in verifier, and our Gatekeeper install had no verification CRDs at all, so you would add Ratify or an external data provider. We used the public Kyverno test images, which come signed, unsigned and signed by a different key. The public key below is the one Kyverno publishes for those test images. Save the policy as kv-verify-image.yaml:

apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
  name: check-image
spec:
  webhookConfiguration:
    timeoutSeconds: 30
  evaluation:
    background:
      enabled: false
  validationActions: [Deny]
  matchConstraints:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: In
          values: ["verify-kv"]
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  matchImageReferences:
    - glob: "ghcr.io/kyverno/test-verify-image*"
  validationConfigurations:
    mutateDigest: true
  attestors:
    - name: cosign
      cosign:
        key:
          data: |
            -----BEGIN PUBLIC KEY-----
            MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8nXRh950IZbRj8Ra/N9sbqOPZrfM
            5/KAQN0/KjHcorm/J5yctVd7iEcnessRQjU917hmKO6JWVGHpDguIyakZA==
            -----END PUBLIC KEY-----
        ctlog:
          insecureIgnoreTlog: true
  validations:
    - expression: >-
        images.containers.map(image, verifyImageSignatures(image, [attestors.cosign])).all(e, e > 0)
      message: failed the image signature verification

The 30 second webhook timeout is deliberate, because the admission controller fetches signatures from the registry during the request. Apply the policy, then start one pod from each test tag:

kubectl apply -f kv-verify-image.yaml
kubectl run signed --image=ghcr.io/kyverno/test-verify-image:signed -n verify-kv
kubectl run unsigned --image=ghcr.io/kyverno/test-verify-image:unsigned -n verify-kv
kubectl get pod signed -n verify-kv -o jsonpath="{.spec.containers[0].image}{\"\n\"}"

The signed pod starts, and mutateDigest has pinned its tag to the verified digest. The unsigned one is refused with the cosign error:

ghcr.io/kyverno/test-verify-image:signed@sha256:b31bfb4d0213f254d361e0079deaaebefa4f82ba7aa76ef82e90b4935ad5b105
Error from server: admission webhook "ivpol.validate.kyverno.svc-fail-finegrained-check-image" denied the request: Policy check-image failed: failed the image signature verification; verification details: image "ghcr.io/kyverno/test-verify-image:unsigned@sha256:74a98f0e4d750c9052f092a7f7a72de7b20f94f176a490088f7a744c76c53ea5", attestor "cosign": failed to verify cosign signatures: no matching signatures: invalid signature when validating ASN.1 encoded signature

The signed-by-someone-else tag failed the same way, which is the case that matters in practice: a valid signature from the wrong key is still a rejection.

Kyverno ImageValidatingPolicy admitting a cosign signed image pinned to a digest and denying unsigned images

Digest pinning is the quiet win here, and you get it for free with mutateDigest. Once the pod spec holds the digest, a later push to the same tag cannot swap the image under a running workload.

Step 8: Read audit results, warn mode and dry run

Both engines reported the legacy nginx pod: Gatekeeper in the constraint status, Kyverno as a PolicyReport. Admission only sees new requests, so both engines also rescan what is already running, and that is how you find the pods created before a policy existed. Gatekeeper writes results into the status of each constraint.

kubectl get k8sallowedrepos only-trusted-registries -o yaml

The relevant part of the status names the legacy pod and its namespace. You can script against totalViolations for alerts.

  totalViolations: 1
  violations:
  - enforcementAction: deny
    group: ""
    kind: Pod
    message: container <legacy-nginx> has an invalid image repo <nginx:1.27>, allowed
      repos are ["ghcr.io/", "registry.k8s.io/"]
    name: legacy-nginx
    namespace: legacy-gk
    version: v1

The same status also showed an enforcementPointsStatus entry for vap.k8s.io in state error with the message K8sNativeValidation engine is missing. It is harmless for Rego templates; it only means Gatekeeper is not generating a native ValidatingAdmissionPolicy for this template.

Kyverno writes one PolicyReport per resource instead. Listing them across namespaces gives you a quick health view of the whole cluster in one command.

kubectl get policyreport -A

The legacy pod shows one failure, found by the background scan process. The ERROR 1 on the pods in policy-test-kv is explained just below:

NAMESPACE        NAME                                   KIND   NAME           PASS   FAIL   WARN   ERROR   SKIP   AGE
legacy-kv        da186421-144f-4a40-bf68-a902b528b831   Pod    legacy-nginx   0      1      0      0       0      5m40s
policy-test-kv   1a850ce3-a638-4131-8633-eb458244a221   Pod    unlabelled     2      0      0      1       0      59s
policy-test-kv   e52941af-b17d-4071-96b0-77cda87d2419   Pod    good-pod       2      0      0      1       0      4m59s

Those errors come from the MutatingPolicy. During a background scan there is no request, so request.userInfo.username does not exist and the report says add-team-labels error failed to evaluate policy: no such key: username. Admission works fine. If the noise bothers you, guard the expression with has(request.userInfo.username) or keep user-based mutations out of background evaluation.

How do you roll a policy out without blocking anyone?

Start every new policy in warn mode, which admits the pod and prints the reason on both engines, because the first scan always finds workloads you forgot about. We created copies of the registry rule in four namespaces:

  • Gatekeeper enforcementAction: warn in warn-gk
  • Gatekeeper enforcementAction: dryrun in dryrun-gk
  • Kyverno validationActions: [Warn, Audit] in warn-kv
  • Kyverno validationActions: [Audit] in audit-kv

What changes between the soft variants and the Step 2 policies? Only the name, the action and the namespace. Save the Gatekeeper dry run constraint as gk-allowedrepos-dryrun.yaml:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
  name: only-trusted-registries-dryrun
spec:
  enforcementAction: dryrun
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    namespaces: ["dryrun-gk"]
  parameters:
    repos:
      - "ghcr.io/"
      - "registry.k8s.io/"

For warn mode, copy that file and change the action and namespace to warn. On the Kyverno side, each soft file is the Step 2 ValidatingPolicy with a new name, the validationActions from the list above, background scanning enabled and the namespace selector pointed at warn-kv or audit-kv. Create the four namespaces and apply the four files:

kubectl create ns warn-gk; kubectl create ns dryrun-gk; kubectl create ns warn-kv; kubectl create ns audit-kv
kubectl apply -f gk-allowedrepos-warn.yaml
kubectl apply -f gk-allowedrepos-dryrun.yaml
kubectl apply -f kv-trusted-registries-warn.yaml
kubectl apply -f kv-trusted-registries-audit.yaml

Then we ran the same bad pod into each of the four namespaces. What would a developer see in each case?

kubectl run bad --image=nginx:1.27 -n warn-gk
kubectl run bad --image=nginx:1.27 -n dryrun-gk
kubectl run bad --image=nginx:1.27 -n warn-kv
kubectl run bad --image=nginx:1.27 -n audit-kv

All four pods were created. The two warn modes print a Warning: line on the client, and the dry run and audit modes print nothing at all:

Warning: [only-trusted-registries-warn] container <bad> has an invalid image repo <nginx:1.27>, allowed repos are ["ghcr.io/", "registry.k8s.io/"]
pod/bad created
pod/bad created
Warning: Policy trusted-registries-warn failed: container image must come from ghcr.io/ or registry.k8s.io/, got: nginx:1.27
pod/bad created
pod/bad created

The silent modes still record the violation. Gatekeeper counts it on the constraint, and Kyverno writes it into the PolicyReport for that namespace. The capture below shows both, with all three Gatekeeper constraints listing one violation each.

Gatekeeper constraint violations and Kyverno PolicyReport results for deny, warn, dryrun and audit modes

Our rollout habit is the same for both: start in warn or audit for a week, read the violations, fix the workloads, then flip to deny. Kyverno PolicyReports are easier to feed into dashboards because they follow the shared wgpolicyk8s.io report format, while the Gatekeeper audit stores at most 20 violations per constraint in status by default. On a busy cluster you will want to export Gatekeeper audit results to logs or metrics instead of reading status.

Step 9: Measure admission latency and footprint

Gatekeeper cost about 5.1 ms per pod and Kyverno about 7.8 ms in this lab, with Gatekeeper using about 163 MiB to Kyverno’s 180 MiB. Timing kubectl from the client is useless here: one hundred server-side dry runs per namespace took 149.9 to 160.6 ms per call, and almost all of that is kubectl starting up. The real cost lives in the apiserver_admission_webhook_admission_duration_seconds metric on the API server, so we read it before and after each batch of 100 dry runs and averaged the delta per webhook. The counts include every request a webhook saw during the batch, not only the pod dry runs, so the means carry a little background traffic. Every batch sends this pod:

apiVersion: v1
kind: Pod
metadata:
  generateName: lat-
  labels:
    owner: lab
spec:
  containers:
    - name: pause
      image: registry.k8s.io/pause:3.10

Save it as good-pod-gen.yaml. It is a compliant pod that passes every policy in all three namespaces. It needs the owner label, or pods-must-have-owner would reject it in policy-test, and generateName lets the same file run a hundred times. Snapshot the metric, run the batch and snapshot again for each namespace:

for ns in nopolicy policy-test policy-test-kv; do
  kubectl get --raw /metrics | grep -E '^apiserver_admission_webhook_admission_duration_seconds_(sum|count)' > /tmp/snap-$ns-before.txt
  for i in $(seq 1 100); do kubectl create -f good-pod-gen.yaml -n $ns --dry-run=server -o name >/dev/null; done
  kubectl get --raw /metrics | grep -E '^apiserver_admission_webhook_admission_duration_seconds_(sum|count)' > /tmp/snap-$ns-after.txt
done

The difference between the two snapshots, sum over count for each webhook name, gives the mean time per call. This awk prints it for one namespace; swap the file names for the others:

awk 'match($0,/name="[^"]+"/){n=substr($0,RSTART+6,RLENGTH-7); k=($0~/_sum/)?"s":"c"; f=(FILENAME==ARGV[1])?"a":"b"; v[f,k,n]+=$NF; seen[n]=1} END{for(n in seen){c=v["b","c",n]-v["a","c",n]; if(c>0 && n~/gatekeeper|kyverno/ && n!~/monitor/) printf "%-45s calls=%d mean=%.2f ms\n", n, c, (v["b","s",n]-v["a","s",n])/c*1000}}' /tmp/snap-policy-test-kv-before.txt /tmp/snap-policy-test-kv-after.txt

Our run used the same snapshot and delta logic inside a small script, twice over, and the filter skips Kyverno’s own monitor-webhooks watcher, which saw only one or two calls per batch. Round one, with the namespace on the left:

nopolicy       mutation.gatekeeper.sh                                                 calls=155   mean=1.48 ms
nopolicy       validation.gatekeeper.sh                                               calls=155   mean=1.73 ms
policy-test    mutation.gatekeeper.sh                                                 calls=156   mean=2.38 ms
policy-test    validation.gatekeeper.sh                                               calls=156   mean=2.68 ms
policy-test-kv mpol.validate.kyverno.svc-fail                                         calls=100   mean=3.22 ms
policy-test-kv mutation.gatekeeper.sh                                                 calls=158   mean=1.64 ms
policy-test-kv validation.gatekeeper.sh                                               calls=158   mean=2.16 ms
policy-test-kv vpol.validate.kyverno.svc-fail-8edb4697                                calls=100   mean=2.23 ms
policy-test-kv vpol.validate.kyverno.svc-fail-bd01e845                                calls=100   mean=2.34 ms

Two patterns stand out in the first round, and the second round landed within 0.5 ms of each total:

  • Gatekeeper is called in every namespace, even nopolicy
  • Kyverno is called only where a policy matches
  • Gatekeeper mutate plus validate: about 5.1 ms per pod
  • Kyverno, one mutate and two validate policies: about 7.8 ms

Gatekeeper pays everywhere because its webhook matches everything and filters inside the controller, so even namespaces with no constraints pay about 3 ms per pod. Kyverno pays only where you scope it, but it pays per policy group, so the cost climbs as you add policies to the same namespace.

Per webhook admission latency for Gatekeeper and Kyverno from apiserver metrics

Single-digit milliseconds will not matter when you run a normal deploy. They matter for clusters that create thousands of pods a minute, such as batch queues or nodes scaled by Karpenter on EKS, where the per-policy Kyverno webhooks add up as the policy count grows. If you run dozens of Kyverno policies against pods, measure this metric on your own cluster before and after, because the lab only had three.

Memory and requests came from kubectl top and the pod specs, after all the policies above were loaded. The working set barely moved during the latency runs.

PodWorking setRequest / limit
gatekeeper-audit87 MiB100m, 512Mi / 512Mi
gatekeeper-controller-manager76 MiB100m, 512Mi / 512Mi
kyverno-admission-controller77 MiB100m, 128Mi / 384Mi
kyverno-reports-controller48 MiB100m, 64Mi / 128Mi
kyverno-background-controller34 MiB100m, 64Mi / 128Mi
kyverno-cleanup-controller21 MiB100m, 64Mi / 128Mi

Kyverno uses slightly more memory in total (about 180 MiB against 163 MiB) but reserves far less: its four pods request 320 MiB together, while the two Gatekeeper pods request 1 GiB. Gatekeeper also installed 17 CRDs plus one per template (19 in our lab), and Kyverno installed 20. Both footprints grow with the number of resources the audit and reports controllers have to cache, so size them from your object count, not from a lab.

Which webhook fails open, and why it matters

Gatekeeper fails open for pods and Kyverno fails closed, so a crashed Kyverno blocks pod creation in matched namespaces. The webhook configurations explain more about day-two behaviour than any feature list. We dumped every validating and mutating webhook after the policies were in place:

kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o json | jq -r '.items[] | .metadata.name as $c | (.webhooks // [])[] | [$c, .name, .failurePolicy, .timeoutSeconds, (.rules|map(.resources|join(","))|join(";")), (.namespaceSelector|tostring)] | @tsv' | cut -c1-260

Five lines of that output decide what happens when a controller pod is down.

  • validation.gatekeeper.sh: Ignore, 3 s, all namespaces
  • check-ignore-label.gatekeeper.sh: Fail, 3 s, namespace creates and updates
  • mutation.gatekeeper.sh: Ignore, 1 s, all namespaces
  • Kyverno vpol and mpol webhooks: Fail, 10 s, only matched namespaces
  • Kyverno ivpol image webhooks: Fail, 30 s

Gatekeeper fails open for workloads: if its controller crashes, pods are admitted unchecked and audit catches them later, although namespace creates and updates are refused until it comes back. Kyverno fails closed: if its admission controller is down, matched namespaces cannot create pods at all. Neither is wrong, but you need to know which one you run before an incident. With Kyverno, scope policies tightly with namespaceSelector, run three admission replicas and keep kube-system out of scope, the same discipline you would apply to Cilium network policies in production.

Admission policy, Pod Security and RBAC also show up together in security exam tasks. Our CKS practice questions cover that side with hands-on tasks, and the CKA practice questions work through the cluster skills these policies build on.

What broke in the lab, and the fixes

Four things broke, and the two Gatekeeper ones looked like success. These are the errors we hit while building the lab. Most of them fail quietly, which is why each one comes with the command that exposes it and the fix.

Error: “Kyverno v1.20 removed execution of legacy kyverno.io policy types”

Any kind: ClusterPolicy or kind: Policy under kyverno.io/v1 is refused on create and update. Rewrite it as a policies.kyverno.io/v1 ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy. Before upgrading a cluster that already runs ClusterPolicies, export them with kubectl get clusterpolicy -o yaml and migrate them first, because the objects stay readable after the upgrade while nothing enforces them.

Error: “Could not ingest Rego: invalid ConstraintTemplate: invalid import: bad import: “rego.v1″”

The template applies without error, but kubectl get constrainttemplate k8srequiredlabels -o jsonpath="{.status.byPod[0].errors}" shows an ingest_error and the constraint never enforces. Dropping the import and keeping the v1 keywords gave a second error, rego_parse_error: unexpected : token: expected \n or ; or }. The legacy rego: field in the template only accepts v0 syntax, the violation[{"msg": msg}] { ... } form used throughout this post. To write v1, move the policy under targets[].code[] with engine: Rego and source.version: "v1". Always check the template status after applying it, because kubectl apply reports success either way.

PolicyReport shows “failed to evaluate policy: no such key: username”

This comes from a MutatingPolicy that reads request.userInfo.username. Admission has a request, but the background scan does not, so every matching pod gets an ERROR result. Admission mutation still works. Guard the field with has() or accept the error entries as noise in your reports.

Deployment shows 0/1 ready with no pods and no error on apply

That is a Gatekeeper constraint that matches Pods only. The Deployment is admitted and the ReplicaSet fails with FailedCreate. Run kubectl get events --field-selector reason=FailedCreate to see the deny message, and extend the constraint to workload kinds so the failure shows up at apply time instead.

Keep reading

Best UI Applications for Managing Docker Containers Containers Best UI Applications for Managing Docker Containers Install Docker and Run Containers on Ubuntu 24.04|22.04 Containers Install Docker and Run Containers on Ubuntu 24.04|22.04 Install UniFi OS Server on Ubuntu 26.04 / 24.04 LTS Containers Install UniFi OS Server on Ubuntu 26.04 / 24.04 LTS Traefik 3.8 Upgrade: Breaking Changes, Yaegi v2 and Helm Test Containers Traefik 3.8 Upgrade: Breaking Changes, Yaegi v2 and Helm Test magpie: One AI Gateway for Claude Code and Codex on Linux AI magpie: One AI Gateway for Claude Code and Codex on Linux Setup Private Docker Registry on Rocky Linux 10 / AlmaLinux 10 AlmaLinux Setup Private Docker Registry on Rocky Linux 10 / AlmaLinux 10

Leave a Comment

Press ESC to close