Module 8 of 16

Policy-as-Code Security

OPA, Kyverno, Gatekeeper, and admission controllers for automated security enforcement

3.5 hours2 labsFree

Start here

Learning objectives

  • Write OPA Rego policies for Kubernetes security
  • Deploy Kyverno for declarative policy enforcement
  • Configure Gatekeeper admission controller
  • Automate compliance checks in CI/CD
POLICY-AS-CODE ENFORCEMENT PIPELINEkubectl applyAPI ServerAuthN + AuthZ (RBAC)passes to admissionAdmission ControllerOPA Gatekeeper / KyvernoEvaluate policiesetcd (saved)Example PoliciesNo privileged containersRequire resource limitsBlock latest tagRequire labelsRejected: violates "no-privileged-containers" policyBlocked BEFORE reaching etcd. Zero impact on cluster.

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

FeatureOPA GatekeeperKyverno
Policy languageRegoYAML (K8s native)
Learning curveHigher (new language)Lower (familiar YAML)
MutationLimitedFull support
GenerationNoYes (auto-create resources)
EcosystemBroader (OPA used beyond K8s)K8s-specific

Real world

Where this shows up

  • Blocking privileged containers via admission control
  • Requiring resource limits on all deployments
  • Automated compliance enforcement in CI/CD
  • Multi-tenant policy isolation

Common mistakes

What usually breaks

  • Deploying policies in Enforce mode without testing in Audit mode first
  • Writing overly broad policies that block legitimate workloads
  • Not versioning policies in Git alongside application code
  • Forgetting to exclude system namespaces (kube-system) from restrictive policies

Tradeoffs

Design choices you should be able to defend

OPA Gatekeeper

Pros

  • Powerful Rego language
  • Broader ecosystem (works beyond K8s)
  • Strong community

Cons

  • Steep learning curve
  • Limited mutation support
  • Separate template + constraint model

Kyverno

Pros

  • Kubernetes-native YAML
  • Easy to learn
  • Full mutation and generation
  • Policy reports built-in

Cons

  • K8s-specific only
  • Less expressive than Rego for complex logic

Key terms

Vocabulary used in this module

Admission Controller

Intercepts API requests after auth, before persistence — can mutate or reject

OPA

Open Policy Agent — general-purpose policy engine

Rego

Declarative policy language used by OPA

Kyverno

Kubernetes-native policy engine using YAML policies

Gatekeeper

Kubernetes admission controller that uses OPA for policy enforcement

Labs

Hands-on labs

30 minIntermediate

Block Insecure Deployments with OPA Gatekeeper

Deploy Gatekeeper and enforce container security policies.

  1. Install OPA Gatekeeper
  2. Create ConstraintTemplate for privileged containers
  3. Deploy a privileged pod — observe rejection
  4. Deploy a compliant pod — observe success
View lab on GitHub
30 minBeginner

Enforce Security with Kyverno

Use Kyverno to require resource limits and block dangerous configurations.

  1. Install Kyverno
  2. Create policies: require limits, block latest tag, require labels
  3. Test with compliant and non-compliant deployments
  4. View policy reports
View lab on GitHub

Recap

Key takeaways

  • Policy-as-code automates security enforcement — no manual reviews needed
  • Admission controllers block insecure configs BEFORE they reach the cluster
  • OPA Gatekeeper uses Rego (powerful, steep learning curve)
  • Kyverno uses YAML (Kubernetes-native, easier adoption)
  • Policies should be tested in CI/CD before deploying to production

Related resources

Keep learning across CodersSecret