Skip to main content

Overview

OPA Gatekeeper validates Kubernetes resources at admission using Rego policies. It extends Open Policy Agent for Kubernetes-native policy enforcement.

Capabilities

  • Validate and mutate K8s resources at admission time via Rego
  • Constraint templates for reusable policy logic
  • Audit mode for detecting existing violations
  • Enforcement actions: deny, dryrun, and warn

Limitations

  • Requires a Kubernetes cluster with Gatekeeper installed
  • Only applicable to Kubernetes workloads — check out Semgrep or CodeQL for application source code, or Checkov for IaC static analysis

Generated Format

  • Language: YAML with embedded Rego
  • Structure: ConstraintTemplate with Rego in spec.targets[].rego and accompanying Constraint resource
  • Execution: Applied to a K8s cluster via kubectl apply

Example Guardrail

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg}] {
          provided := {label | input.review.object.metadata.labels[label]}
          required := {label | label := input.parameters.labels[_]}
          missing := required - provided
          count(missing) > 0
          msg := sprintf("Missing required labels: %v", [missing])
        }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-team-label
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Namespace"]
  parameters:
    labels: ["team"]
Learn more at OPA Gatekeeper documentation and constraint templates.