系统学习 演练学习路径:35 个 lab 的难度排序、4 周基础计划与复盘方法

搭建 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"]

验证

回滚

常见坑

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 策略一开始就设为 deny 有什么风险?
  2. 没有豁免系统命名空间,可能造成什么后果?
  3. 想立即停止拦截,应该把 enforcementAction 改回什么?
答案
  1. 误伤现有工作负载,应先在 dryrun 模式下观察审计结果。
  2. Gatekeeper 自身可能被拦截。
  3. 改回 dryrun,立即停止拦截。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令