Gatekeeper: Kubernetes admission

Constraints and templates in-cluster.

Advanced14 min · lesson 9 of 12

OPA Gatekeeper integrates OPA into Kubernetes as a validating (and mutating) admission controller. Instead of running policy in CI, Gatekeeper evaluates every resource as it is created or updated in the cluster and rejects violations at admission — so a non-compliant pod never gets scheduled, no matter how it was submitted. It packages policy as Kubernetes CRDs: a ConstraintTemplate holds the Rego, and Constraints instantiate it with parameters and a scope.

GATEKEEPER ADMISSION
1resource applied
pod/namespace create or update
2admission webhook
Gatekeeper intercepts the request
3evaluate Constraint
instantiates ConstraintTemplate Rego
4admit or reject
enforcementAction: deny / dryrun / warn
Every resource is checked at admission; a violation is rejected before it is ever scheduled.
constrainttemplate.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8srequiredlabels }
spec:
crd:
spec: { names: { kind: K8sRequiredLabels }, validation: { openAPIV3Schema: { properties: { labels: { type: array } } } } }
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
required := input.parameters.labels[_]
not input.review.object.metadata.labels[required]
msg := sprintf("missing required label: %v", [required])
}
constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels # the kind the template defined
metadata: { name: must-have-owner }
spec:
match: { kinds: [{ apiGroups: [""], kinds: ["Namespace"] }] }
parameters: { labels: ["owner"] }
enforcementAction: deny # or dryrun / warn

Audit, dryrun, and rollout

Gatekeeper also audits existing resources against constraints (not just new ones), reporting violations already in the cluster — invaluable when adopting a policy on a running cluster. Roll out with enforcementAction: dryrun or warn first to see who fails without blocking, fix the workloads, then switch to deny. This is the same audit-before-enforce discipline as Pod Security; flipping straight to deny on a busy cluster breaks the next deploy.

Audit before deny, and mind the fail mode
Set constraints to dryrun/warn first and read the audit results before deny, or you reject every non-compliant deploy at once. Also understand Gatekeeper’s failurePolicy: if the webhook is down and failurePolicy is Fail, admissions can be blocked cluster-wide; if Ignore, policy is silently skipped. Choose deliberately and monitor the webhook’s health — an admission controller is in the critical path of every deploy.