搭建 OPA Gatekeeper 策略中心

适用场景

需要用 Rego 编写 Kubernetes 准入策略,统一限制镜像来源、资源限制、标签和权限。Gatekeeper 适合已经有 OPA 经验或需要复杂策略逻辑的团队。

前置条件

步骤

  1. 安装 Gatekeeper:
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
  1. 创建 ConstraintTemplate:
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
  1. 创建 Constraint:
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
  1. 查看审计结果并切换为拒绝:
kubectl get k8srequiredlabels require-team -o yaml
kubectl get constrainttemplate
kubectl patch k8srequiredlabels require-team \
  --type merge -p '{"spec":{"enforcementAction":"deny"}}'
  1. 对系统命名空间配置豁免:
spec:
  match:
    excludedNamespaces: ["kube-system", "gatekeeper-system"]

验证

回滚

常见坑

相关命令