You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Gatekeeper禁止在未配置含limits.cpu与limits.memory的ResourceQuota的Namespace中创建Pods?

修正你的Gatekeeper配置以实现Namespace资源配额校验

我来帮你排查下现有配置里的核心问题,然后给出能满足需求的修正方案:

  1. 同步配置的API版本错误:ResourceQuota的稳定API版本是v1,而非你写的v1beta1,这会导致Gatekeeper无法正确同步配额数据到本地inventory。
  2. Rego规则逻辑偏差:当前规则仅检查Namespace下是否存在ResourceQuota,但没验证配额是否包含limits.cpu和limits.memory限制;另外ns_exists函数逻辑完全走偏了,它在判断配额名称是否等于Namespace名称,这和需求毫无关系。
  3. 冗余同步对象:同步Pod是不必要的,我们只需要同步Namespace和ResourceQuota数据即可。

1. 修正后的同步配置(sync.yaml)

apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
  name: config
  namespace: "gatekeeper-system"
spec:
  sync:
    syncOnly:
      - group: ""
        version: "v1"
        kind: "Namespace"
      - group: ""
        version: "v1"
        kind: "ResourceQuota"

2. 修正后的ConstraintTemplate

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sresoucequota
spec:
  crd:
    spec:
      names:
        kind: k8sResouceQuota
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sresoucequota

        violation[{"msg": msg}] {
          # 仅对Pod创建请求进行校验
          input.request.kind.kind == "Pod"
          pod_ns := input.request.object.metadata.namespace

          # 检查当前Namespace下是否存在符合要求的ResourceQuota
          not exists_valid_resourcequota(pod_ns)

          # 构造明确的违规提示
          msg := sprintf("Pod <%v> cannot be created in namespace <%v>: the namespace must have a ResourceQuota defining both limits.cpu and limits.memory", [input.request.object.metadata.name, pod_ns])
        }

        # 辅助函数:校验指定Namespace下存在包含CPU和内存限制的ResourceQuota
        exists_valid_resourcequota(ns) {
          # 遍历该Namespace下所有ResourceQuota对象
          rq := data.inventory.namespace[ns]["v1"]["ResourceQuota"][_]
          # 确保配额同时包含limits.cpu和limits.memory的硬限制
          rq.spec.hard["limits.cpu"]
          rq.spec.hard["limits.memory"]
        }

3. 原Constraint配置可保留(无需修改)

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: k8sResouceQuota
metadata:
  name: namespace-must-have-resourcequota
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    excludedNamespaces:
      - kube-system
      - kube-public
      - kube-node-lease
      - default
      - gatekeeper-system
      - kubernetes-dashboard

配置说明

  • 同步配置修正了ResourceQuota的API版本,确保Gatekeeper能正确拉取集群中的配额数据。
  • Rego规则新增的辅助函数专门校验配额是否包含所需的CPU和内存限制,只有当Namespace下完全没有这类配额时才会触发拦截。
  • 违规提示信息更清晰,能直接告知用户问题所在,方便排查调整。

内容的提问来源于stack exchange,提问作者Prageetika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:12:44