Skip to main content

Command Palette

Search for a command to run...

OPA & Gatekeeper Reference: Rego Policies, ConstraintTemplate, Audit & conftest CI Gates

Published
1 min read
M

25+ years building backend systems, APIs, and infrastructure. Now focused on helping developers stay on top of software releases. Building ReleaseRun — because reading changelogs shouldn't be a full-time job.

OPA and Gatekeeper patterns for K8s policy enforcement.

ConstraintTemplate: the Rego lives here

spec:
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package requiredlabels

        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])
        }

Constraint: deploy the policy with parameters

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: RequiredLabels
spec:
  enforcementAction: dryrun   # start with dryrun, switch to deny
  match:
    kinds: [{apiGroups: ["*"], kinds: ["Namespace"]}]
    excludedNamespaces: [kube-system, gatekeeper-system]
  parameters:
    labels: ["team", "environment"]

Check violations across existing resources

kubectl describe requiredlabels require-team-label
# Status.Violations shows all existing resources that violate the policy

Use enforcementAction: dryrun first — you'll often find violations in existing resources that you'd break if you jumped straight to deny.

Gatekeeper vs Kyverno

  • Gatekeeper: Rego (powerful, hard to learn), enterprise standard, OPA everywhere else
  • Kyverno: YAML (easy, no new language), great for simpler policies, K8s-native

conftest for CI

# Validate K8s YAML against OPA policies before kubectl apply:
conftest test deployment.yaml   # exit 1 if any deny rule matches

Full reference (Rego fundamentals, OPA standalone HTTP API for microservice authz, bundle polling, Envoy ExtAuthz pattern, Rego unit tests with opa test): releaserun.com/opa-gatekeeper-reference

More from this blog

R

ReleaseRun Blog

297 posts