需要用 Rego 编写 Kubernetes 准入策略,统一限制镜像来源、资源限制、标签和权限。Gatekeeper 适合已经有 OPA 经验或需要复杂策略逻辑的团队。
kubectl。helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper gatekeeper/gatekeeper \
--namespace gatekeeper-system --create-namespace
kubectl -n gatekeeper-system get pods
kubectl apply -f - <<'EOF'
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}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("缺少标签: %v", [missing])
}
EOF
kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team
spec:
enforcementAction: dryrun
match:
kinds:
- apiGroups: ["apps"]
kinds: ["Deployment"]
parameters:
labels: ["team", "env"]
EOF
kubectl get k8srequiredlabels require-team -o yaml
kubectl get constrainttemplate
kubectl patch k8srequiredlabels require-team \
--type merge -p '{"spec":{"enforcementAction":"deny"}}'
spec:
match:
excludedNamespaces: ["kube-system", "gatekeeper-system"]
enforcementAction 改回 dryrun,立即停止拦截。match.kinds 的 apiGroups 写错,策略不生效。kubectl — 管理模板、约束和审计helm — 安装和升级opa — 本地测试 Regoconftest — CI 中验证清单