Open Policy Agent (OPA) Gatekeeper 是一个用于在 Kubernetes 中强制执行入场策略的工具。这些策略是使用 OPA 提供的策略语言 Rego 来定义的。以下是使用 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
这个 Rego 策略检查 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"