How do you write a custom Checkov policy?
IntermediateHands-onCheckov
Answer
Short answer
Write custom checks in YAML (simple attribute and connection rules) or Python (complex logic), put them in a folder, and run Checkov with --external-checks-dir. Typical uses: company tagging standards, approved regions or instance types, naming conventions.
YAML example: every resource must have an owner and cost-center tag
# policies/require_tags.yaml
metadata:
id: "CKV2_SHOP_1"
name: "Ensure resources have owner and cost-center tags"
category: "GENERAL_SECURITY"
severity: "MEDIUM"
definition:
and:
- cond_type: attribute
resource_types: [aws_instance, aws_s3_bucket, aws_db_instance]
attribute: tags.owner
operator: exists
- cond_type: attribute
resource_types: [aws_instance, aws_s3_bucket, aws_db_instance]
attribute: tags.cost-center
operator: exists
Python example: only approved instance types
# policies/approved_instance_types.py
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
class ApprovedInstanceTypes(BaseResourceCheck):
def __init__(self):
super().__init__(name="Use approved EC2 instance types", id="CKV_SHOP_2",
categories=[CheckCategories.GENERAL_SECURITY], supported_resources=["aws_instance"])
def scan_resource_conf(self, conf):
allowed = {"t3.micro", "t3.small", "m6i.large"}
return CheckResult.PASSED if conf.get("instance_type", [""])[0] in allowed else CheckResult.FAILED
check = ApprovedInstanceTypes()
checkov -d infra/ --external-checks-dir policies/
What to say in the interview
"Custom Checkov policies in YAML for attribute or relationship rules like mandatory tags, or Python for richer logic like approved instance types, loaded with --external-checks-dir. That turns company standards into automated PR checks."
More on Checkov
What is Checkov and how do you scan Terraform with it?BeginnerWhat is IaC security scanning and why is it needed?BeginnerWhat is Checkov?BeginnerHow do you scan Terraform code with Checkov?BeginnerWhy scan the Terraform plan with Checkov instead of only the .tf files?IntermediateHow do you scan Kubernetes manifests and Dockerfiles with Checkov?Beginner