
Scanning Infrastructure-as-Code for Misconfigurations With Python: Checkov Under the Hood
Most teams run Checkov as a black box: point it at a Terraform folder, read the pass/fail list, move on. That's fine for day-to-day use. But Checkov is a Python tool, and once you understand how it actually works, you can write your own checks for the rules that matter to your org specifically — the ones no public scanner ships with, because they only make sense inside your own infrastructure conventions.
This post covers two things: what Checkov does internally when you run it, and how to write a real custom check in Python for a rule your team actually needs.
What Checkov actually does
Checkov is a static analysis tool for infrastructure-as-code. It reads Terraform, CloudFormation, Kubernetes manifests, Serverless configs, and a handful of other formats, and checks each resource against a library of security and compliance rules — things like "don't leave an S3 bucket public" or "don't open a security group to 0.0.0.0/0."
Here's the part that matters for writing your own checks: Checkov doesn't run string matching or regex against your files. It parses them into an abstract graph. Each resource block becomes a node. Each reference between resources (a security group ID referenced by an EC2 instance, a subnet referenced by a load balancer) becomes an edge. Checkov builds this graph once, resolves variables and locals across it, and then runs every registered check against the resulting resource configuration dictionaries.
That graph step is why Checkov can catch things a plain linter can't — it can tell you an RDS instance is reachable from the public internet through a chain of security group references, not just that one security group looks permissive in isolation.
Each individual check, though, is just a small Python class. It receives one resource's parsed configuration as a dictionary and returns PASSED or FAILED. That's the part you can extend.
Writing a custom check
Checkov ships with hundreds of built-in checks, but they're necessarily generic — they can't know your org requires every billable resource to carry an Environment tag with one of three approved values (dev, staging, prod), so a stray typo like Prod or production doesn't silently break your cost allocation reports. That's exactly the kind of rule worth writing yourself.
Checkov's custom checks subclass BaseResourceCheck and implement one method: scan_resource_conf, which receives the resource's configuration and returns a CheckResult.
from typing import Any, Dict
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
# <!-- verify: import path for BaseResourceCheck can shift between Checkov
# major versions — confirm against the version pinned in your requirements.txt -->
class EnforceEnvironmentTag(BaseResourceCheck):
"""Fails any resource missing a valid Environment tag."""
ALLOWED_VALUES = {"dev", "staging", "prod"}
def __init__(self) -> None:
name = "Ensure resource has a valid Environment tag"
check_id = "CKV_ORG_1"
supported_resources = ["aws_instance", "aws_s3_bucket", "aws_db_instance"]
categories = [CheckCategories.GENERAL_SECURITY]
super().__init__(
name=name,
id=check_id,
categories=categories,
supported_resources=supported_resources,
)
def scan_resource_conf(self, conf: Dict[str, Any]) -> CheckResult:
tags = conf.get("tags")
if not tags or not isinstance(tags, list):
return CheckResult.FAILED
tag_block = tags[0]
if not isinstance(tag_block, dict):
return CheckResult.FAILED
environment = tag_block.get("Environment")
if not environment:
return CheckResult.FAILED
# Terraform values often arrive wrapped in a single-item list
value = environment[0] if isinstance(environment, list) else environment
if value not in self.ALLOWED_VALUES:
return CheckResult.FAILED
return CheckResult.PASSED
check = EnforceEnvironmentTag()A few things worth noticing:
check_iduses theCKV_ORG_prefix. That's a convention, not a requirement — it just keeps your custom checks visibly separate from Checkov's built-inCKV_AWS_IDs in output and reports.supported_resourceslimits the check to resource types where anEnvironmenttag actually makes sense. Checkov only callsscan_resource_conffor matching resource types; everything else is skipped automatically.- The last line,
check = EnforceEnvironmentTag(), instantiates and registers the check. Checkov's check registry picks it up via this instantiation when it loads the file — there's no separate registration step.
Save that file somewhere outside Checkov's own package, for example custom_checks/EnforceEnvironmentTag.py in your repo.
Running it
Point Checkov at your Terraform directory and tell it where your custom checks live with --external-checks-dir:
checkov -d . --framework terraform --external-checks-dir ./custom_checksOutput looks like this (trimmed for length):
Check: CKV_ORG_1: "Ensure resource has a valid Environment tag"
FAILED for resource: aws_instance.web
File: /main.tf:12-20
Calling File: /main.tf:0-0
12 | resource "aws_instance" "web" {
13 | ami = "ami-0c55b159cbfafe1f0"
14 | instance_type = "t3.micro"
15 |
16 | tags = {
17 | Name = "web-server"
18 | Environment = "Prod"
19 | }
20 | }
Check: CKV_AWS_8: "Ensure all data stored in the Launch configuration or instance Elastic Blocks Store is securely encrypted"
PASSED for resource: aws_instance.web
Passed checks: 1, Failed checks: 1, Skipped checks: 0The failure is real: the tag value is Prod, not prod, so it doesn't match ALLOWED_VALUES. That's precisely the kind of drift a human reviewer skims past but a Python set lookup never will.
Reading the output
Three things to check every time, especially in CI:
- The check ID and name tell you which rule fired — built-in (
CKV_AWS_*,CKV_K8S_*) or yours (CKV_ORG_*). - The resource and file:line point straight at the offending block, so there's no hunting through a large
.tffile. - The summary line (
Passed checks: X, Failed checks: Y) is what you gate CI on. Checkov exits non-zero when any check fails, socheckov -d . --external-checks-dir ./custom_checks || exit 1in a pipeline step is enough to block a merge on a real violation — including your own custom ones, right alongside the built-in library.
For CI, add --compact to shorten the output, or -o json if you want to parse results programmatically into a dashboard or Slack notification.
Where to go from here
The pattern above generalizes to almost any org-specific rule: required tags, naming conventions, mandatory encryption settings on a specific internal module, disallowed instance types in certain environments. If you can express it as "look at this resource's config dict and decide PASSED or FAILED," it's a Checkov check.
Checkov's own repo has a full library of built-in checks worth reading before you write a new one — your rule might already exist, or you might find a close example to copy the structure from. If you write one worth sharing, Checkov also accepts community check contributions upstream.

Experienced DevOps Engineer proficient in Python, Docker, Kubernetes, CI/CD, and cloud technologies. Specialized in automating processes and building scalable infrastructure for seamless development and deployment.


