Security policies should be code: version-controlled, testable, reviewable, and automatically enforced. Policy-as-code replaces manual security reviews and hopeful checklists with automated admission control that blocks insecure configurations before they reach the cluster.
OPA and Rego
Open Policy Agent (OPA) is the CNCF-graduated policy engine. Policies are written in Rego, a declarative language designed for structured data evaluation.
# Block privileged containers
package kubernetes.admission
deny[msg] {
input.request.kind.kind == "Pod"
container := input.request.object.spec.containers[_]
container.securityContext.privileged == true
msg := sprintf("Privileged containers not allowed: %s", [container.name])
}
Kyverno
Kyverno uses Kubernetes-native YAML instead of Rego. No new language to learn. Policies are Kubernetes resources that can validate, mutate, and generate configurations.
# Kyverno: require resource limits on all containers
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-resource-limits
spec:
validationFailureAction: Enforce
rules:
- name: check-limits
match:
any:
- resources:
kinds: ["Pod"]
validate:
message: "Resource limits are required for all containers"
pattern:
spec:
containers:
- resources:
limits:
memory: "?*"
cpu: "?*"
Gatekeeper vs Kyverno
| Feature | OPA Gatekeeper | Kyverno |
|---|---|---|
| Policy language | Rego | YAML (K8s native) |
| Learning curve | Higher (new language) | Lower (familiar YAML) |
| Mutation | Limited | Full support |
| Generation | No | Yes (auto-create resources) |
| Ecosystem | Broader (OPA used beyond K8s) | K8s-specific |