> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kyverno Kubernetes Native Policy Management

> Overview of Kyverno Kubernetes native policy engine, its validate mutate and generate rule types, usage patterns, comparison with Gatekeeper, and best practices for auditing and debugging.

Kyverno is a Kubernetes-native policy engine and a practical alternative to Gatekeeper. Its major advantage: policies are authored as native Kubernetes YAML (no new language to learn). If you can write Kubernetes manifests, you can write Kyverno policies.

This guide explains Kyverno's three rule types — validate, mutate, and generate — shows common policy patterns, and helps you decide when to choose Kyverno versus Gatekeeper.

![A slide titled "Learning Objectives" with three numbered points. It lists: understand Kyverno rule types (validate, mutate, generate); implement policy patterns like image registry enforcement and required labels; and compare Kyverno and Gatekeeper to choose the right policy tool.](https://mintcdn.com/kodekloud-c4ac6d9a/jFwNGqGMK4QeJs-g/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Security-and-Policy-Enforcement/Kyverno-Kubernetes-Native-Policy-Management/learning-objectives-kyverno-gatekeeper-compare.jpg?fit=max\&auto=format\&n=jFwNGqGMK4QeJs-g\&q=85\&s=071789f64d49d5f5bbefa8010132fb68)

Kyverno supports validate, mutate, and generate rules within a single `ClusterPolicy` or `Policy` resource:

* validate — enforce structural and field constraints (expressed with Kubernetes YAML patterns).
* mutate — modify objects before they are persisted (apply defaults, add labels, inject sidecars, set imagePullPolicy).
* generate — create new Kubernetes resources automatically in response to events (e.g., new Namespace creation).

![A presentation slide titled "Three Rule Types in One Policy" showing Kyverno policy types with three icons labeled 01 Validate, 02 Mutate, and 03. Under Mutate there are short notes about adding defaults and modifying resources before they're stored.](https://mintcdn.com/kodekloud-c4ac6d9a/jFwNGqGMK4QeJs-g/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Security-and-Policy-Enforcement/Kyverno-Kubernetes-Native-Policy-Management/kyverno-three-rule-types-validate-mutate.jpg?fit=max\&auto=format\&n=jFwNGqGMK4QeJs-g\&q=85\&s=f66ba1a36cfc703ffb00c669833cad99)

## Quick reference: rule types

| Rule type | Purpose | Typical use cases |
| - | - | - |
| Validate | Reject or allow resources based on YAML pattern checks | Enforce label presence, image registry policy, resource limits |
| Mutate | Modify resources before persistence (mutating admission webhook) | Add defaults, inject labels or sidecars, normalize fields |
| Generate | Create new resources in response to matched objects | Create default NetworkPolicy, ResourceQuota, ServiceAccount per namespace |

## 1) Validate

Validation rules examine resources and reject non-compliant objects. Kyverno uses YAML pattern matching (with wildcards) rather than a separate policy language like Rego.

Example: Require container images to come from a corporate registry.

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: restrict-image-registries
spec:
  validationFailureAction: Enforce
  rules:
    - name: validate-registries
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: >-
          Images must be from
          registry.company.com
        pattern:
          spec:
            containers:
              - image: "registry.company.com/*"
```

Tips:

* `validationFailureAction: Enforce` blocks non-compliant resources. Start with `Audit` to log violations without blocking.
* `match` scopes which resources the rule applies to.
* `pattern` uses Kyverno's YAML pattern matching. For simple to moderate checks this method is concise and easy to maintain.
* If your requirements need arbitrarily complex queries or computations, consider Gatekeeper (OPA + Rego), which is more expressive.

## 2) Mutate

Mutate rules modify objects before they are persisted. This works via Kyverno's mutating admission webhook and is a strong differentiation from Gatekeeper.

Example: Add a default `managed-by: platform-team` label to Deployments and Services when absent.

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-default-labels
spec:
  rules:
    - name: add-team-label
      match:
        any:
          - resources:
              kinds: ["Deployment", "Service"]
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              managed-by: platform-team
```

Details and best practices:

* `patchStrategicMerge` behaves like a Kubernetes strategic-merge patch. It will add or update the provided label.
* To avoid overwriting an existing label value, use conditional mutation logic or JSON Patch (RFC 6902) with Kyverno's `patchesJson6902`.
* Mutations happen before validation webhooks, enabling a pattern where you apply defaults (mutate) and then assert required fields (validate).

Combining mutate + validate in a single policy (common pattern):

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: ensure-managed-by-label
spec:
  rules:
    - name: add-team-label
      match:
        any:
          - resources:
              kinds: ["Deployment", "Service"]
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              managed-by: platform-team

    - name: require-team-label
      match:
        any:
          - resources:
              kinds: ["Deployment", "Service"]
      validate:
        message: "Resource must have managed-by: platform-team label"
        pattern:
          metadata:
            labels:
              managed-by: "platform-team"
```

Behavior: On create, the mutate rule adds the label if missing; the validate rule ensures it's present, so deliberate removal will be rejected.

## 3) Generate

Generate rules automatically create resources when a matching object is created. This unique Kyverno capability helps enforce secure defaults and reduce onboarding friction.

Example: Create a default deny NetworkPolicy for each new Namespace, referencing the namespace name via Kyverno variables.

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: default-deny-ingress
spec:
  rules:
    - name: generate-default-netpol
      match:
        any:
          - resources:
              kinds: ["Namespace"]
      generate:
        kind: NetworkPolicy
        apiVersion: networking.k8s.io/v1
        name: default-deny-ingress
        namespace: "{{request.object.metadata.name}}"
        data:
          spec:
            podSelector: {}
            policyTypes: ["Ingress"]
```

Common generate use cases:

* Default `NetworkPolicy` to lock down new namespaces
* `ResourceQuota` and `LimitRange` per namespace
* Create `ServiceAccount` and RBAC bindings automatically for teams

![A presentation slide titled "Kyverno vs Gatekeeper: When to Use Which" showing a three-column comparison of "Comparison Point", "Kyverno", and "OPA Gatekeeper." It lists differences for Complex Logic (Kyverno: limited pattern matching; Gatekeeper: full Rego), Architecture (Kyverno: single ClusterPolicy; Gatekeeper: ConstraintTemplate + Constraint), and Exam Weight (Kyverno: medium simpler YAML; Gatekeeper: high deeper Rego).](https://mintcdn.com/kodekloud-c4ac6d9a/jFwNGqGMK4QeJs-g/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Security-and-Policy-Enforcement/Kyverno-Kubernetes-Native-Policy-Management/kyverno-vs-gatekeeper-when-to-use.jpg?fit=max\&auto=format\&n=jFwNGqGMK4QeJs-g\&q=85\&s=40b560615ea53cf8f3ae96368596841b)

When to choose Kyverno vs Gatekeeper:

* Use Kyverno when you want mutation (defaults, injections) and straightforward validation expressed in YAML patterns. It’s fast to author and maintain for platform policies.
* Use Gatekeeper (OPA + Rego) when you need highly expressive, complex validation logic that requires full programmatic capability.
* Both can run in the same cluster; evaluate per-policy which tool is the best fit.

Best practice: author policies in `Audit` mode first. Review PolicyReports for violations, iterate on the policy, and then switch the policy to `Enforce`.

## Debugging Kyverno

Common commands and checks:

```sh theme={null}
# List all cluster policies and check readiness
kubectl get clusterpolicy
# Example output columns:
# NAME                        ADMISSION   BACKGROUND   READY
# Check PolicyReports (audit-mode violations)
kubectl get policyreport -A
kubectl get clusterpolicyreport

# See violation details for a specific namespace
kubectl describe policyreport -n payments

# Check Kyverno admission controller logs if webhooks are failing
kubectl logs -n kyverno deployment/kyverno
```

Troubleshooting hints:

* `READY: false` for a ClusterPolicy usually indicates a YAML syntax error or invalid policy field — check the Kyverno controller logs for details.
* If policies do not seem to target objects you expect, verify the `match`/`exclude` criteria and resource `kinds`.
* If webhooks are failing, inspect the Kyverno pod logs and the webhook configuration in `kubectl get validatingwebhookconfigurations` / `kubectl get mutatingwebhookconfigurations`.

![A presentation slide titled "Key Takeaways" with three numbered points. It summarizes Kyverno: it uses native Kubernetes YAML, has three rule types (validate, mutate, generate), and recommends starting in Audit mode, reviewing PolicyReports, fixing issues, then switching to Enforce.](https://mintcdn.com/kodekloud-c4ac6d9a/jFwNGqGMK4QeJs-g/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Security-and-Policy-Enforcement/Kyverno-Kubernetes-Native-Policy-Management/kyverno-key-takeaways-validate-mutate-generate.jpg?fit=max\&auto=format\&n=jFwNGqGMK4QeJs-g\&q=85\&s=866f784a0d97a6283a3f3b82963de9ad)

Summary

* Kyverno policies are native Kubernetes YAML—no separate policy language required.
* Kyverno supports validate, mutate, and generate in a single policy resource.
* Start in `Audit` mode, review PolicyReports, iterate, then move to `Enforce`.
* Use Kyverno for mutation and common platform validation patterns; use Gatekeeper (Rego) for complex validation logic. They can coexist in the same cluster.

Links and references

* Kyverno official docs: [https://kyverno.io/](https://kyverno.io/)
* Gatekeeper (OPA) docs: [https://open-policy-agent.github.io/gatekeeper/](https://open-policy-agent.github.io/gatekeeper/)
* Rego policy language: [https://www.openpolicyagent.org/docs/latest/policy-language/rego/](https://www.openpolicyagent.org/docs/latest/policy-language/rego/)
* Kubernetes admission controllers: [https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/)
* Kyverno Best Practices: [https://kyverno.io/docs/best-practices/](https://kyverno.io/docs/best-practices/)

> **[Watch Video](https://learn.kodekloud.com/user/courses/prep-course-certified-cloud-native-platform-engineer-cnpe/module/35a7fadb-02d8-4557-a819-2e4dcfa970cc/lesson/1a5a6874-6438-434c-a731-163beffe04ea)**


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.