如何为Checkov自定义Python策略传入输入参数?
为Checkov自定义策略添加输入参数
1. 修改自定义策略类,支持参数接收
先调整你的策略类,让它能接收外部参数。以检查资源名称前缀为例,通过重写__init__方法定义可配置的参数:
from checkov.terraform.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories class CustomResourceNameCheck(BaseResourceCheck): def __init__(self, name="Custom Resource Name Check", id="CKV_CUSTOM_1001", categories=[CheckCategories.GENERAL_SECURITY], supported_resources=["*"], allowed_prefixes=None): super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) # 设置默认值,外部未传参时使用 self.allowed_prefixes = allowed_prefixes or ["prod-", "staging-"] def scan_resource_conf(self, conf): # 从Terraform配置中获取资源名称(不同资源字段可能不同,按需调整) resource_name = conf.get("name", [None])[0] if not resource_name: return CheckResult.UNKNOWN # 校验名称是否符合指定前缀 if any(resource_name.startswith(prefix) for prefix in self.allowed_prefixes): return CheckResult.PASSED return CheckResult.FAILED
2. 通过配置文件传递参数
Checkov支持通过项目根目录的checkov.yaml配置文件给自定义策略传参,配置示例:
custom_checks: - name: Custom Resource Name Check id: CKV_CUSTOM_1001 allowed_prefixes: ["dev-", "test-"]
运行Checkov时,它会自动读取这个配置,将参数注入到对应的策略类中。
3. 动态传参(环境变量/命令行)
如果需要按需动态传参,可以用环境变量实现:
运行Checkov前设置环境变量:
export CUSTOM_ALLOWED_PREFIXES="dev-,test-"
修改策略类读取环境变量:
import os class CustomResourceNameCheck(BaseResourceCheck): def __init__(self, ...): super().__init__(...) # 从环境变量读取参数并处理 env_prefixes = os.getenv("CUSTOM_ALLOWED_PREFIXES") if env_prefixes: self.allowed_prefixes = env_prefixes.split(",") else: self.allowed_prefixes = ["prod-", "staging-"]
4. 验证参数生效
运行Checkov时指定自定义策略目录和要检查的Terraform计划JSON:
checkov -f terraform_plan.json --check CKV_CUSTOM_1001 --custom-checks-dir custom_checks
此时策略会使用你传入的参数执行检查,比如dev-app会通过校验,random-app会触发失败。
关键注意点
- 确保策略类的参数名和配置文件/环境变量的定义一致,避免拼写错误
- 复杂参数(如嵌套列表、字典)可直接用YAML格式在配置文件中定义
- 针对不同Terraform资源,调整
scan_resource_conf中读取字段的逻辑(比如某些资源用name,某些用identifier)
内容的提问来源于stack exchange,提问作者kini_dot
相关产品推荐
相关产品推荐

