Course contentsShow
← Cloud and Infrastructure
Lesson 2892 of 2,98963. Infrastructure TestingFree lesson

Writing OPA Policies for Kubernetes

Creating OPA policies to validate Kubernetes manifests and enforce resource requirements.

Writing OPA Policies for Kubernetes

What You'll Learn

You'll learn how to create OPA policies using Rego to validate Kubernetes manifests and enforce resource requirements before they're applied to your cluster.

Why Validate Kubernetes Manifests?

Think of OPA policies as automated quality gatekeepers for your Kubernetes resources. Just as a building inspector checks that construction meets safety codes before occupancy, OPA policies verify that your manifests meet organizational standards before deployment. This prevents misconfigured workloads from entering your cluster.

Creating Validation Policies

When writing OPA policies for Kubernetes, you're evaluating the manifest structure against your rules. A common policy might enforce that all containers specify CPU and memory limits:

package kubernetes.admission

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    not container.resources.limits.memory
    msg := sprintf("Container '%s' must specify memory limits", [container.name])
}

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    not container.resources.limits.cpu
    msg := sprintf("Container '%s' must specify CPU limits", [container.name])
}

This policy inspects incoming Pod creation requests. The input.request.object represents the Kubernetes manifest being evaluated. If any container lacks resource limits, the policy generates a denial message.

Enforcing Security Standards

You can layer multiple checks—requiring non-root users, blocking privileged containers, or mandating specific labels:

deny[msg] {
    input.request.kind.kind == "Deployment"
    not input.request.object.metadata.labels.owner
    msg := "Deployments must have an 'owner' label"
}

These policies integrate with admission controllers, blocking non-compliant resources at submission time.

Key Takeaway: OPA policies for Kubernetes validate manifests against organizational standards using Rego rules that inspect resource definitions and enforce requirements like resource limits, security constraints, and metadata compliance before deployment.