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

Checkov自定义策略检测K8s Deployment注解异常:添加注解仍报失败

解决Checkov自定义策略检测缺失default-container注解的问题

你的策略核心逻辑没问题,但问题出在注解键的属性访问方式上。因为kubectl.kubernetes.io/default-container包含多个点,直接用.分隔会被Checkov解析成多层嵌套属性(比如把kubectl当成annotations下的子属性,而非整个注解键),导致永远检测不到注解存在。

修正后的策略文档

---
metadata:
  id: "CKV2_KCDC_1"
  name: "Ensure all Deployments have default-container annotation"
  category: "KUBERNETES"
definition:
  and:
    - cond_type: filter
      value:
        - Deployment
      operator: within
      attribute: kind
    - cond_type: attribute
      resource_types:
        - Deployment
      attribute: "metadata.annotations['kubectl.kubernetes.io/default-container']"
      operator: exists

关键修改点

把原策略中的attribute: "metadata.annotations.kubectl.kubernetes.io/default-container"改成attribute: "metadata.annotations['kubectl.kubernetes.io/default-container']",用方括号加单引号包裹包含特殊字符的注解键,让Checkov正确识别这是一个完整的注解名称,而非多层属性路径。

验证步骤

  1. 给Deployment添加目标注解的示例清单:
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: test-deploy
      annotations:
        kubectl.kubernetes.io/default-container: test-container
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: test
      template:
        metadata:
          labels:
            app: test
        spec:
          containers:
          - name: test-container
            image: nginx:alpine
    
  2. 运行Checkov检测命令:
    checkov -f your-deployment.yaml -c CKV2_KCDC_1 --external-checks-dir ./your-policy-dir
    

此时添加了注解的Deployment会通过检测,未添加的则会被标记为失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:34:59