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

Kyverno ClusterPolicy例外规则对Deployment不生效的解决方法

解决方案:让带特定注解的Deployment通过ClusterPolicy验证

问题的核心原因是:Deployment作为Pod的控制器,其注解不会自动传递给创建的Pod。如果你的ClusterPolicy是针对Pod资源做镜像标签校验,而PolicyException仅匹配Pod的注解,那么Deployment生成的Pod因没有对应注解会被拦截;如果ClusterPolicy针对Deployment资源校验,则需直接豁免带有指定注解的Deployment本身。

分场景处理:


场景1:你的ClusterPolicy目标是Pod资源

此时需要通过Pod的ownerReferences关联到所属Deployment,检查Deployment的注解来实现豁免。使用ClusterPolicyException(集群级豁免)或PolicyException(命名空间级豁免):

# 集群级豁免示例(适用于所有命名空间)
apiVersion: kyverno.io/v1
kind: ClusterPolicyException
metadata:
  name: exempt-deployments-by-annotation
spec:
  exceptions:
    - policyName: 你的ClusterPolicy名称  # 替换为实际的ClusterPolicy名称
      ruleNames:
        - 你的规则名称  # 替换为ClusterPolicy中对应的规则名
  match:
    any:
      - resources:
          kinds:
            - Pod
          # 匹配由Deployment创建的Pod
          selector:
            matchExpressions:
              - key: ownerReferences.kind
                operator: In
                values:
                  - Deployment
  exclude:
    any:
      - resources:
          kinds:
            - Pod
          # 检查所属Deployment是否带有目标注解
          preconditions:
            - key: "{{ owner.metadata.annotations.com.xxx/exempt }}"  # 替换为你的特定注解键
              operator: Equals
              value: "true"  # 替换为注解对应的值

场景2:你的ClusterPolicy目标是Deployment资源

直接匹配带有指定注解的Deployment即可,无需关联Pod:

# 集群级豁免示例
apiVersion: kyverno.io/v1
kind: ClusterPolicyException
metadata:
  name: exempt-deployments-by-annotation
spec:
  exceptions:
    - policyName: 你的ClusterPolicy名称
      ruleNames:
        - 你的规则名称
  match:
    any:
      - resources:
          kinds:
            - Deployment
          annotations:
            com.xxx/exempt: "true"  # 替换为你的特定注解键值对

如果仅需豁免单个命名空间的Deployment,改用PolicyException并指定namespace字段:

apiVersion: kyverno.io/v1
kind: PolicyException
metadata:
  name: exempt-deployments-by-annotation
  namespace: 目标命名空间  # 替换为需要豁免的命名空间
spec:
  exceptions:
    - policyName: 你的ClusterPolicy名称
      ruleNames:
        - 你的规则名称
  match:
    any:
      - resources:
          kinds:
            - Deployment
          annotations:
            com.xxx/exempt: "true"

验证生效方法

  1. 创建带有目标注解的Deployment:
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: test-deployment
      annotations:
        com.xxx/exempt: "true"
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: test
      template:
        metadata:
          labels:
            app: test
        spec:
          containers:
            - name: test-container
              image: 未带校验标签的镜像名
    
  2. 检查Deployment和Pod状态:
    kubectl get deployment test-deployment
    kubectl get pods
    
  3. 查看Kyverno策略报告确认无违规:
    kubectl get policyreport -A
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:43:15