> ## 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.

# Prerequisites Bonus Video Lecture

> Introduction to Kyverno, a Kubernetes native policy engine that validates and mutates resources using CRDs to enforce governance and best practices

Hey everyone, it's Srinivas from KodeKloud. In this lesson we’ll learn about Kyverno — a Kubernetes-native policy engine that validates and mutates Kubernetes resources using familiar Kubernetes-style CRDs. Kyverno helps enforce organization policies (labels, image sources, resource limits, replica counts, network policies, etc.) so that resource creation and updates comply with governance and best practices.

We’ll cover:

* What Kyverno is
* How Kyverno works inside the API server admission flow
* Example policies (validation and mutation) and a short demo workflow

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-icon-list-quick-demo.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=279f2e6e99dd47e6881fcf89b2643a82" alt="The image contains an icon on the left and a list on the right with the headings: &#x22;What is Kyverno?&#x22;, &#x22;How Kyverno Works?&#x22;, and &#x22;Quick Demo: Some Example Policies.&#x22; The background is black." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-icon-list-quick-demo.jpg" />
</Frame>

## Why use Kyverno?

Consider a simple Deployment manifest you might apply to a cluster:

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: myapp
          image: nginx
```

When you run `kubectl apply`, Kubernetes validates manifest syntax and authorizations, but it won't enforce organization-specific policies by default. Requiring labels, disallowing public registries, enforcing resource requests/limits, or rejecting `:latest` images manually is error-prone and hard to scale.

Automating policy enforcement with Kyverno ensures consistency, lowers developer feedback latency, and preserves compliance without slowing delivery.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/flowchart-organization-manager-platform-kubernetes.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=78c1a1a380d913e204485e9351d1a6b2" alt="The image depicts a flowchart connecting an organization, a manager or CEO, and a platform team or developers, highlighting concepts like governance, best practices, consistency, lower latency, and agility, with the Kubernetes logo featured prominently." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/flowchart-organization-manager-platform-kubernetes.jpg" />
</Frame>

## Common policy examples

Below are typical policies organizations enforce via Kyverno:

| Policy intent                                  | Target resource  | Example pattern                                        |
| ---------------------------------------------- | ---------------- | ------------------------------------------------------ |
| Require images from an approved registry       | Pods/Deployments | `kodekloud.io/*`                                       |
| Ensure globally unique Ingress hostnames       | Ingress          | (match host uniqueness via custom logic or validation) |
| Require resource requests/limits on containers | Pods/Deployments | validate `spec.containers[*].resources`                |
| Deny traffic unless allowed by NetworkPolicy   | Pods/Namespaces  | deny when no NetworkPolicy applies                     |

You can adopt these examples to fit your environment (private registry prefix, minimum replicas, allowed namespaces, etc.).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/image-requirements-ingress-pods-traffic.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=1a72866c1148a01b22acf98ee055c60a" alt="The image lists four requirements: images must be from an approved repository, ingress hostnames must be globally unique, pods must have resource limits, and traffic must be denied without network policies." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/image-requirements-ingress-pods-traffic.jpg" />
</Frame>

## Where Kyverno integrates with Kubernetes

Incoming API requests pass through authentication and authorization, then the admission controller pipeline. Admission webhooks can mutate or validate requests before objects are persisted to etcd. Kyverno runs as an admission webhook (a third-party policy agent) and can perform mutations and validations in the mutating and validating admission stages.

If a request complies with Kyverno policies, the webhook allows it; otherwise it is denied or logged (depending on policy action).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-api-request-flowchart-admission.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=4626106859725a01b06f26fbbaae1cdb" alt="The image is a flowchart illustrating the process of handling an API request with Kyverno, detailing steps like authentication, admission, and validation before storing in ETCD. It highlights the role of a Policy Agent in the mutating and validating admission stages." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-api-request-flowchart-admission.jpg" />
</Frame>

## Installing Kyverno

Kyverno is distributed via Helm. Installing creates the necessary CustomResourceDefinitions (CRDs) and deploys Kyverno controllers plus the admission webhook.

Add the Helm repo, refresh, and inspect the chart:

```bash theme={null}
helm repo add kyverno https://kyverno.github.io/kyverno/
helm repo update
helm search repo kyverno -l
```

A straightforward install (adjust replica counts for HA):

```bash theme={null}
helm install kyverno kyverno/kyverno -n kyverno --create-namespace \
  --set admissionController.replicas=3 \
  --set backgroundController.replicas=2 \
  --set cleanupController.replicas=2 \
  --set reportsController.replicas=2
```

Verify the Kyverno CRDs:

```bash theme={null}
kubectl get crd | grep kyverno
```

Kyverno also provides an optional chart that ships pre-configured policies implementing the Kubernetes Pod Security Standards:

```bash theme={null}
helm install kyverno-policies kyverno/kyverno-policies -n kyverno
```

## Policy basics (CRDs and actions)

Kyverno introduces CRDs such as `ClusterPolicy` and `Policy`. Policies can:

* Validate requests (deny or audit violations).
* Mutate requests before admission.
* Generate reports.

Use `validationFailureAction` to control enforcement:

<Callout icon="lightbulb" color="#1CB2FE">
  Set `validationFailureAction` to `Enforce` to deny non-compliant requests, or `Audit` to allow requests but record violations for reporting.
</Callout>

### Example 1 — Require a `team` label on Deployments

ClusterPolicy that enforces a non-empty `team` label on Deployments:

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-deployment-team-label
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-deployment-team-label
      match:
        any:
          - resources:
              kinds:
                - Deployment
      validate:
        message: "You must have label `team` for all deployments"
        pattern:
          metadata:
            labels:
              team: "?*"
```

Key points:

* `match` targets resource kinds (here: `Deployment`).
* `validate.message` is returned when the rule is violated.
* The pattern `team: "?*"` requires a non-empty string for the `team` label.

Apply the policy and verify:

```bash theme={null}
kubectl apply -f label-policy.yaml
kubectl get clusterpolicy
```

Creating a Deployment without the `team` label will be denied by Kyverno’s admission webhook:

```bash theme={null}
kubectl apply -f deployment.yaml
# Example webhook response:
# admission webhook "validate.kyverno.svc" denied the request:
# resource Deployment/default/nginx-deployment was blocked due to the following policies
# require-deployment-team-label:
#   require-deployment-team-label: 'validation error: You must have label `team` for all deployments. rule require-deployment-team-label failed at path /metadata/labels/team/'
```

Add `labels: { team: frontend }` to succeed.

### Example 2 — Minimum replicas validation

Require at least 3 replicas for Deployments:

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: minimum-replicas
spec:
  validationFailureAction: Enforce
  rules:
    - name: minimum-replicas
      match:
        any:
          - resources:
              kinds:
                - Deployment
      validate:
        message: "Deployment must specify at least 3 replicas"
        pattern:
          spec:
            replicas: ">=3"
```

Kyverno evaluates `spec.replicas` and denies requests with replicas \< 3.

### Mutation example — set imagePullPolicy when image uses :latest

Kyverno can mutate incoming requests. Example: set `imagePullPolicy` when a container uses the `:latest` tag:

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: set-image-pull-policy
spec:
  rules:
    - name: set-image-pull-policy
      match:
        any:
          - resources:
              kinds:
                - Pod
      mutate:
        patchStrategicMerge:
          spec:
            containers:
              - (image): "*:latest"
                imagePullPolicy: "IfNotPresent"
```

Notes:

* `mutate.patchStrategicMerge` merges values into the incoming object.
* The special key `(image): "*:latest"` matches container entries where `image` ends with `:latest` and sets `imagePullPolicy`.

## Demo workflow (commands)

1. Install Kyverno using the Helm commands above.
2. Create and apply example ClusterPolicy YAML files (labels, replicas, mutation).
3. Attempt to apply Deployments/Pods that violate policies to observe Kyverno denying them.
4. Switch `validationFailureAction` from `Audit` to `Enforce` after validating policy impact.

Kyverno documentation covers validate/mutate rules, wildcard patterns, strategic merge, and more. For pattern matching details see: [https://kyverno.io/docs/writing-policies/validate/](https://kyverno.io/docs/writing-policies/validate/)

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-documentation-validating-rules-screenshot.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=08703d0e3653e19a8ce88706c7415b50" alt="The image is a screenshot of a webpage from the Kyverno documentation, specifically the section on validating rules, with detailed explanations and a sidebar menu containing navigation links." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/kyverno-documentation-validating-rules-screenshot.jpg" />
</Frame>

## Additional policy examples

* Deny `:latest` or require an explicit tag:

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: no-latest-tag-policy
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-image-tag
      match:
        any:
          - resources:
              kinds:
                - Pod
      validate:
        message: "Container image must include an explicit tag, e.g., image:nginx:1.23.0"
        pattern:
          spec:
            containers:
              - image: "*:*"
    - name: disallow-latest-tag
      match:
        any:
          - resources:
              kinds:
                - Pod
      validate:
        message: "Cannot use the `:latest` tag"
        pattern:
          spec:
            containers:
              - image: "!*:latest"
```

* Allow only images from a private registry (example uses `kodekloud.io`):

```yaml theme={null}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: deny-public-registries
spec:
  validationFailureAction: Enforce
  rules:
    - name: allow-private-registry
      match:
        any:
          - resources:
              kinds:
                - Pod
      validate:
        message: "Unknown image registry. Images must be pulled from kodekloud.io."
        pattern:
          spec:
            containers:
              - image: "kodekloud.io/*"
```

The pattern `kodekloud.io/*` enforces that the image string begins with the private registry prefix — replace with your registry (for example: `myregistry.internal/*`).

## Hands-on tips

* Start with `validationFailureAction: Audit` to measure impact before switching to `Enforce`.
* For lists like `containers`, Kyverno’s wildcard patterns and strategic merge keys (e.g., `(image)`) let you match items by key.
* Consider enabling Kyverno’s pre-configured Pod Security Standard policies to get a baseline. See Kubernetes Pod Security Standards: [https://kubernetes.io/docs/concepts/security/pod-security-standards/](https://kubernetes.io/docs/concepts/security/pod-security-standards/)

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GUk2-1Y8Wvqthmtm/images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/installation-process-user-helm-kubernetes.jpg?fit=max&auto=format&n=GUk2-1Y8Wvqthmtm&q=85&s=4abf13c7d60b04cd1349780aaa1791a9" alt="The image is a flow diagram depicting an installation process involving a user, Helm, and Kubernetes-related components. It shows an arrow sequence from the user to Helm, and then to a group of puzzle-piece icons and a Kubernetes logo." width="1920" height="1080" data-path="images/Learn-By-Doing-Kubernetes-Policies-with-Kyverno/Introduction-Prerequisites/Prerequisites-Bonus-Video-Lecture/installation-process-user-helm-kubernetes.jpg" />
</Frame>

## Summary

Kyverno is a Kubernetes-native policy engine that integrates with the admission webhook pipeline to validate and mutate resources using native Kubernetes CRDs (`ClusterPolicy` and `Policy`). With Kyverno you can automate enforcement of labels, image registries and tags, resource constraints, replica counts, network controls, and more. Installing via Helm is simple, and Kyverno offers pre-built policy bundles for common best practices. Start with `Audit` mode to validate impact, then move to `Enforce` when ready.

Happy experimenting with Kyverno — it’s a practical way to automate policy enforcement across your cluster.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-policies-with-kyverno/module/a3370f08-e378-4285-9305-52025206031a/lesson/88f594b7-4413-486b-9d5a-e1c9615efa5d" />
</CardGroup>
