Gatekeeper: OPA for Kubernetes admission
Architecture
Gatekeeper runs in the cluster (namespace gatekeeper-system) and registers itself with the API server as a validating admission webhook (and optionally a mutating one). For every matching create/update request, the API server sends an AdmissionReview to Gatekeeper, which evaluates the relevant policies and returns allowed/denied with messages.
Components:
- Webhook pods (run several replicas) — answer admission requests.
- Audit controller — periodically (default about every 60 seconds) evaluates existing resources against constraints and writes violations into each Constraint's
status— catches things created before the policy existed or that bypassed admission. - Controller manager — compiles ConstraintTemplates into CRDs.
ConstraintTemplate and Constraint
Gatekeeper splits a policy into two parts:
- ConstraintTemplate — the reusable Rego logic plus a parameter schema. Creating one defines a new CRD kind.
- Constraint — an instance of that kind: which resources it applies to (
match), its parameters, and its enforcement action.
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, "details": {"missing_labels": missing}}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("you must provide labels: %v", [missing])
}
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: namespaces-must-have-owner
spec:
enforcementAction: dryrun # deny | dryrun | warn
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
excludedNamespaces: ["kube-system", "gatekeeper-system"]
parameters:
labels: ["owner", "cost-centre"]
Notes:
- In Gatekeeper templates, the object is at
input.review.object(andinput.review.oldObjectfor updates), parameters atinput.parameters. - Rules must be named
violationand produce objects with amsg(optionaldetails). - The template above uses the classic Rego syntax common in the Gatekeeper library.
matchsupportskinds,namespaces,excludedNamespaces,labelSelector,namespaceSelector,scope(Namespaced/Cluster).
Enforcement actions
| Action | Effect |
|---|---|
deny |
Request rejected with the message |
warn |
Request allowed; kubectl shows a warning |
dryrun |
Request allowed; violations only recorded by audit |
The Gatekeeper policy library
The community library has ready-made templates — use them instead of writing your own where possible:
K8sAllowedRepos— images only from approved registries (e.g. your ECR prefix).K8sContainerLimits/K8sRequiredResources— CPU/memory limits and requests required.K8sPSPPrivilegedContainer,K8sPSPHostNamespace,K8sPSPCapabilities,K8sPSPReadOnlyRootFilesystem... — Pod Security equivalents.K8sRequiredLabels,K8sRequiredProbes,K8sBlockNodePort,K8sDisallowedTags(latest),K8sUniqueIngressHost,K8sBlockLoadBalancer.
Referential policies: syncing cluster data
Some policies need other objects — "Ingress hosts must be unique across the cluster" needs all existing Ingresses. Configure Gatekeeper's sync (the Config resource, or SyncSet in newer versions) to replicate selected kinds into OPA's cache, available under data.inventory:
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata: { name: config, namespace: gatekeeper-system }
spec:
sync:
syncOnly:
- { group: "networking.k8s.io", version: "v1", kind: "Ingress" }
- { group: "", version: "v1", kind: "Namespace" }
match:
- excludedNamespaces: ["kube-system"]
processes: ["*"]
Gatekeeper also supports external data providers for lookups outside the cluster (e.g. verifying image signatures).
Mutation
Gatekeeper's mutation CRDs change objects at admission:
- Assign — set a field (e.g.
securityContext.runAsNonRoot: true, defaultimagePullPolicy). - AssignMetadata — add labels/annotations (only additions).
- ModifySet — add/remove items in lists (e.g. drop
NET_RAWcapability). - AssignImage — rewrite image registries/tags.
Mutation is powerful but can surprise developers ("my manifest says X but the cluster has Y") and makes GitOps diffs noisy. Keep mutations minimal, documented, and prefer validation with good messages.
Testing Gatekeeper policies
- gator CLI:
gator testevaluates resources against templates and constraints offline;gator verifyruns suites of test cases — run it in CI on the policy repo. - Deploy to a non-prod cluster in
dryrunand read audit results before enforcing.