Skip to content

Kyverno: YAML-native policies for Kubernetes admission and mutation

Install Kyverno and write validate, mutate, and generate ClusterPolicy resources in pure YAML, with audit-mode rollout and policy reporting.

You looked at OPA Gatekeeper and decided the team would not maintain Rego in production — too easy to write a 30-line policy that nobody can review six months later. Kyverno offers the same admission-control capability but in pure YAML, with native mutate and generate verbs alongside validate. This article is the operating procedure: install, write a couple of representative policies, roll out in audit, then enforce.

How to verify

The Kyverno controllers should be running:

kubectl -n kyverno get pods

ClusterPolicies and Policies should be listable:

kubectl get clusterpolicy
kubectl get policy -A

The PolicyReport CRD shows per-namespace violations:

kubectl get policyreport -A
kubectl get clusterpolicyreport

A test resource that violates a policy should be rejected (or audited):

kubectl run privileged-test --image=nginx --privileged --dry-run=server -o yaml | kubectl apply -f -

What’s happening

Kyverno is an admission webhook plus a set of background controllers. The webhook handles validate, mutate, and verifyImages rules on incoming requests; the background reconcilers handle generate rules (creating downstream resources like default NetworkPolicies in every new namespace) and audit mode (scanning existing cluster resources and writing PolicyReports).

A ClusterPolicy (cluster-scoped) or Policy (namespace-scoped) contains one or more rules. Each rule has a match (which resources it applies to), an optional exclude (carve-outs), and exactly one of validate, mutate, generate, or verifyImages. The schema is OpenAPI-like and you write the desired shape directly — no DSL. Kyverno also supports JMESPath expressions for variables and a small set of helper functions (length(@), regex_match, etc.).

The audit/enforce split is per-policy via spec.validationFailureAction (Audit or Enforce). Audit mode writes PolicyReports but does not block; Enforce blocks at the webhook. The recommended rollout is the same as Gatekeeper’s: Audit first until reports are clean, then promote.

The procedure

  1. Install via the Helm chart.

    helm repo add kyverno https://kyverno.github.io/kyverno/
    helm install kyverno kyverno/kyverno \
      --namespace kyverno \
      --create-namespace \
      --version 3.3.0 \
      --set replicaCount=3 \
      --set backgroundController.replicas=2 \
      --set reportsController.replicas=2 \
      --set cleanupController.replicas=2

    Optionally install the standard policy bundle:

    helm install kyverno-policies kyverno/kyverno-policies \
      --namespace kyverno \
      --set podSecurityStandard=restricted \
      --set validationFailureAction=Audit
  2. Write a validate policy. Example: refuse pods without resource limits.

    apiVersion: kyverno.io/v1
    kind: ClusterPolicy
    metadata:
      name: require-resource-limits
    spec:
      validationFailureAction: Audit
      background: true
      rules:
        - name: validate-resources
          match:
            any:
              - resources:
                  kinds: [Pod]
          validate:
            message: 'CPU and memory limits are required'
            pattern:
              spec:
                containers:
                  - resources:
                      limits:
                        cpu: '?*'
                        memory: '?*'

    The '?*' matches any non-empty value.

  3. Write a mutate policy. Example: set a default priorityClassName on Deployments in app namespaces.

    apiVersion: kyverno.io/v1
    kind: ClusterPolicy
    metadata:
      name: default-priority-class
    spec:
      rules:
        - name: set-priority
          match:
            any:
              - resources:
                  kinds: [Deployment]
                  namespaces: [app, app-staging]
          mutate:
            patchStrategicMerge:
              spec:
                template:
                  spec:
                    priorityClassName: production-medium

    Mutate runs at admission; existing resources are not retroactively modified.

  4. Write a generate policy. Example: drop a baseline NetworkPolicy into every new app namespace.

    apiVersion: kyverno.io/v1
    kind: ClusterPolicy
    metadata:
      name: default-deny-egress
    spec:
      generateExistingOnPolicyUpdate: false
      rules:
        - name: generate-default-deny
          match:
            any:
              - resources:
                  kinds: [Namespace]
                  selector:
                    matchLabels:
                      env: app
          generate:
            apiVersion: networking.k8s.io/v1
            kind: NetworkPolicy
            name: default-deny-egress
            namespace: '{{request.object.metadata.name}}'
            synchronize: true
            data:
              spec:
                podSelector: {}
                policyTypes: [Egress]
                egress:
                  - to:
                      - namespaceSelector:
                          matchLabels:
                            kubernetes.io/metadata.name: kube-system

    synchronize: true means Kyverno reconciles the generated resource — delete it manually, it comes back.

  5. Check PolicyReports for non-compliance.

    kubectl get policyreport -A
    kubectl describe policyreport polr-ns-app

    Each report lists the resource, the policy, the rule, and whether it passed, failed, or warned.

  6. Promote to Enforce when reports are clean.

    kubectl patch cpol require-resource-limits \
      --type merge \
      -p '{"spec":{"validationFailureAction":"Enforce"}}'

    Future violating admissions are blocked. Background scans continue to write reports for existing resources.

Operational notes

  • background: true runs the policy against existing resources on a schedule. It’s how audit reports stay current after a deployed-before-policy resource exists. Without it, audit only catches admission-time decisions.
  • PolicyReports are noisy for big clusters. A cluster with 10k pods and 30 rules produces a lot of report data; the reports-controller has a built-in TTL. Tune cleanupController to keep etcd lean.
  • patchStrategicMerge vs patchesJson6902. Strategic merge is easier to read but does not handle arrays the way JSON Patch does. Use JSON Patch for ordered-array mutations (e.g. injecting a sidecar into containers).
  • generate rules are not idempotent across policy renames. Renaming a policy that generated a NetworkPolicy leaves orphaned NetworkPolicies. Use generateExistingOnPolicyUpdate: true carefully and budget for cleanup.
  • Image verification needs the cosign integration. verifyImages rules pull keys from a Secret or trust root and reject unsigned/untrusted images. Pair with a signed-image policy in your CI to make this practical.

Stack Harbor authors and operates the Kyverno policy catalogue on customer clusters — the validate-mutate-generate split tuned to the workload mix, PolicyReports surfaced through the central observability stack, and the Audit-to-Enforce promotion that does not break a deploy day. See how we deliver that within managed Kubernetes operations, and compare with opa-gatekeeper-policies if Rego is the right fit instead.