The original author of this page is Guillaume
Open Policy Agent (OPA) Gatekeeper is a tool used to enforce admission policies in Kubernetes. These policies are defined using Rego, a policy language provided by OPA. Below is a basic example of a policy definition using OPA Gatekeeper:
regoCopy codepackage k8srequiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[label]}
missing := required - provided
count(missing) > 0
msg := sprintf("Required labels missing: %v", [missing])
}
default allow = false
This Rego policy checks if certain labels are present on Kubernetes resources. If the required labels are missing, it returns a violation message. This policy can be used to ensure that all resources deployed in the cluster have specific labels.
To use this policy with OPA Gatekeeper, you would define a ConstraintTemplate and a Constraint in Kubernetes:
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
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[label]}
missing := required - provided
count(missing) > 0
msg := sprintf("Required labels missing: %v", [missing])
}
default allow = false
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: ensure-pod-has-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
labels:
requiredLabel1: "true"
requiredLabel2: "true"
In this YAML example, we define a ConstraintTemplate to require labels. Then, we name this constraint ensure-pod-has-label
, which references the k8srequiredlabels
ConstraintTemplate and specifies the required labels.
When Gatekeeper is deployed in the Kubernetes cluster, it will enforce this policy, preventing the creation of pods that do not have the specified labels.