You can write a Checkov policy with an LLM in under a minute, and the draft will look like the examples in the Checkov docs. That is the problem. In our lab, three of the first drafts never ran at all, and Checkov still exited 0. Three more ran, reported results, and missed security groups that open SSH to the internet. A green Checkov run proves almost nothing about a new custom check. An LLM Checkov custom check is a draft until Checkov has loaded it, run it, and flagged the misconfigurations you planted in Terraform you own.
This guide runs that loop on one organization rule: SSH (TCP port 22) may only be reachable from the bastion range 10.20.0.0/24. Every message and result below came from our lab: Checkov 3.4.14, the current release on PyPI (published December 1), installed with pip into a virtual environment and run against a Terraform fixture we wrote. We checked the policy formats against the Python custom policies and YAML custom policies docs before drafting anything. The broken drafts were written for this guide to reproduce mistakes models commonly make. They are not a captured model transcript, and no model was called in the lab. Checkov's output is the evidence.
Authorized infrastructure only. Scan Terraform for accounts you own or are engaged to assess. The fixture below is never applied; Checkov reads it as static files. Keep real account IDs, CIDR ranges, hostnames and secrets out of prompts.
What we ran, and what we didn't
- Checkov 3.4.14 from PyPI (
pip install checkov==3.4.14), Python 3.13, on Linux.checkov --versionprinted3.4.14. - One Terraform fixture (
tf/main.tf) with 10 resources: four planted violations, five compliant resources and one egress rule that must be ignored. Two small fixtures test variables (tf-vars/) and a bastion subnet plus IPv6 (tf-subnet/). - Eight drafts: three YAML policies and five Python checks, all loaded with
--external-checks-dirand run alone with-cso built-in checks stay out of the results. - A validator script that turns Checkov's JSON output into
OK,WRONGorNOT LOADED.
We did not run terraform plan or scan plan JSON, did not use the Prisma Cloud platform, and did not test Kubernetes, CloudFormation or Checkov's secrets scanning. In the output below we removed the ASCII banner, blank lines and the Guide: URLs on built-in checks, and in a few places we cut a long list with "...". Nothing else was changed.
How to write a Checkov policy with an LLM
Treat every draft as untrusted and ask two questions, in order:
- Did Checkov load it and run it? Look for your check ID in the results. An unsupported YAML operator, a Python exception at import time and a missing check instance all end the same way in our runs: no results for the check and exit code 0. A passing build is not evidence the check ran.
- Does it fail exactly the resources you planted, and nothing else? Write the expected
FAILEDandPASSEDlist before you prompt, then diff. Most of the dangerous drafts in this post passed question 1.
# 1. Run only your check, so built-in results don't hide it
checkov -d tf --external-checks-dir checks -c CKV_LAB_1 --compact
# 2. Compare against planted answers (script below)
./check_policy.sh checks CKV_LAB_1 expected.txt
The -c flag (--check) restricts the run to the IDs you list. Without it, every built-in check that applies runs too. On our 10-resource fixture that was 61 results (41 passed, 20 failed), and the one line you care about is easy to miss.
Step 1: Plant the answers in a Terraform fixture you own
Write the fixture first, with comments saying which resources must fail. Ours covers the ways SSH gets opened in real AWS Terraform:
# PLANTED: a second ingress block opens SSH to the internet.
resource "aws_security_group" "admin" {
name = "lab-admin"
description = "Admin access"
vpc_id = "vpc-0lab"
ingress {
description = "SSH from bastion"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.20.0.0/24"]
}
ingress {
description = "temporary vendor access"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
# PLANTED: a port range that includes 22, from an office range that is not the bastion.
resource "aws_security_group" "jump_legacy" {
...
ingress {
from_port = 0
to_port = 1024
protocol = "tcp"
cidr_blocks = ["198.51.100.0/24"]
}
}
# PLANTED: standalone rule resource, not an inline block.
resource "aws_vpc_security_group_ingress_rule" "batch_ssh" {
security_group_id = aws_security_group.batch.id
from_port = 22
to_port = 22
ip_protocol = "tcp"
cidr_ipv4 = "0.0.0.0/0"
}
# PLANTED: older aws_security_group_rule style, all protocols from anywhere.
resource "aws_security_group_rule" "legacy_all" {
type = "ingress"
security_group_id = aws_security_group.legacy.id
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
The compliant side matters as much. app_ssh allows SSH from the bastion only. web allows HTTPS (443) from anywhere, which is fine. web_admin is the near-miss: one block allows 443 from 0.0.0.0/0 and another allows 22 from the bastion, so the bad CIDR and the SSH port appear in the same resource but in different blocks. legacy_egress is an egress rule to anywhere, which this policy must ignore. The two empty groups, batch and legacy, must pass.
All three resource types are current in the AWS provider. The provider's aws_security_group docs recommend the standalone aws_vpc_security_group_ingress_rule resource over inline ingress blocks. A policy that only reads inline blocks misses the style the provider tells people to use.
The expected results, written before any draft:
FAILED aws_security_group.admin
FAILED aws_security_group.jump_legacy
FAILED aws_vpc_security_group_ingress_rule.batch_ssh
FAILED aws_security_group_rule.legacy_all
PASSED aws_security_group.app_ssh
PASSED aws_security_group.batch
PASSED aws_security_group.legacy
PASSED aws_security_group.web
PASSED aws_security_group.web_admin
PASSED aws_security_group_rule.legacy_egress
Check the built-in policy before you write one. Checkov already ships CKV_AWS_24. On this fixture it caught three of the four:
$ checkov -d tf -c CKV_AWS_24 --compact --quiet
terraform scan results:
Passed checks: 6, Failed checks: 3, Skipped checks: 0
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_security_group.admin
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_vpc_security_group_ingress_rule.batch_ssh
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_security_group_rule.legacy_all
exit=1
It passed jump_legacy, which opens SSH to 198.51.100.0/24. That is correct for its stated rule (no SSH from 0.0.0.0/0), and it is the gap a "bastion only" rule exists to close. Write a custom check for rules that are specific to your organization, not to re-create one that already exists. The Terraform policy index lists the built-ins.
Step 2: Pick YAML or Python, then prompt with the real interface
Checkov takes custom policies in two formats, and they are not interchangeable. The custom policies overview says Python policies check configuration attributes, while YAML policies check attributes and connections between resources.
- YAML: a
metadatablock (name, an ID in theCKV2_form, a category from a fixed list, optional severity) and adefinitionbuilt fromattribute,connection,resourceandfilterblocks joined withand,orandnot. Operators come from a fixed list:equals,contains,within,greater_than,is_trueand so on. - Python: a class that extends
BaseResourceCheck, setsname,id,supported_resourcesandcategories, implementsscan_resource_conf(conf), and ends with a module-level instance (check = MyCheck()). The docs' example ofconfshows every value wrapped in a list, such as"allocated_storage": [5].
Our rule needs "some ingress block opens port 22 and the same block has a CIDR outside the bastion range." Keep that word "same" in mind. It decides which format works, and Step 4 shows why.
A prompt that produces usable drafts:
Write one Checkov custom check in Python for Checkov 3.4. Rule: AWS security group ingress that reaches TCP port 22 (including port ranges that contain 22 and protocol "-1") must only come from 10.20.0.0/24. Cover inline
ingressblocks onaws_security_group,aws_security_group_rulewithtype = "ingress", andaws_vpc_security_group_ingress_rule(attributesip_protocol,cidr_ipv4,cidr_ipv6). Extendcheckov.terraform.checks.resource.base_resource_check.BaseResourceCheck, useCheckCategories.NETWORKING, IDCKV_LAB_1, and end the file withcheck = SSHFromBastionOnly(). Checkov passes every attribute value wrapped in a list, for example{"from_port": [22], "cidr_blocks": [["10.20.0.0/24"]]}. Return the file only.
Each constraint maps to a failure below. The resource list stops the model from checking inline blocks only. "Port ranges" and -1 stop an exact == 22 match. The category name, the base class path and the closing instance line prevent the three drafts that never ran. And the sample conf shape prevents the most common silent failure in this post.
Step 3: Drafts Checkov skips, with exit code 0
These failures print something, but none of them fails the build. In CI, with output folded, each one looks like a clean scan.
An operator that doesn't exist. Models write not_in because it reads naturally. It isn't in the YAML operator list:
definition:
cond_type: "attribute"
resource_types:
- "aws_security_group"
attribute: "ingress.*.cidr_blocks"
operator: "not_in"
value:
- "0.0.0.0/0"
$ checkov -d tf --external-checks-dir drafts/y1 -c CKV2_LAB_1 --compact
2026-12-02 07:48:38,908 [MainThread ] [WARNI] Failed to parse check id 'CKV2_LAB_1' from file ssh_bastion_only.yaml: solver type SolverType.ATTRIBUTE with operator not_in is not supported. Skipping.
... (8 warnings in total)
exit=0
"Skipping" is the key word. There was no results section at all, and the exit code was 0. The real operators are not_within for list membership and not_contains for list contents.
A category that doesn't exist. CheckCategories.NETWORK sounds right. The enum member is NETWORKING:
$ checkov -d tf --external-checks-dir drafts/p1 -c CKV_LAB_1 --compact
2026-12-02 07:48:47,062 [MainThread ] [ERROR] Cannot load external check 'SSHFromBastionOnly' from drafts/p1/SSHFromBastionOnly.py
Traceback (most recent call last):
...
AttributeError: type object 'CheckCategories' has no attribute 'NETWORK'. Did you mean: 'NETWORKING'?
... (the same error 20 times)
exit=0
Python even suggests the fix. Checkov logged the traceback, skipped the check, scanned nothing for it, and returned 0.
No check instance. The docs end every Python check with a line like check = RDSEncryption(). A draft that defines the class correctly but drops that last line produced this:
$ checkov -d tf --external-checks-dir drafts/p4 -c CKV_LAB_1 --compact
exit=0
No warning, no error, no results. Without the instance, the check never registered. That's the worst of the three, because nothing in the log hints that the check exists. If you only look at the exit code, all three drafts "pass."
Step 4: Drafts that run and miss the misconfiguration
These drafts load, produce results and fail the build on something. That makes them look finished.
Comparing list-wrapped values as scalars. This is the most natural Python a model writes:
def scan_resource_conf(self, conf):
for rule in conf.get("ingress", []):
if rule.get("from_port") == 22:
for cidr in rule.get("cidr_blocks", []):
if cidr != BASTION_CIDR:
return CheckResult.FAILED
return CheckResult.PASSED
Checkov hands the check {"from_port": [22], "cidr_blocks": [["10.20.0.0/24"]], ...} for each ingress block, so [22] == 22 is false every time:
$ checkov -d tf --external-checks-dir drafts/p2 -c CKV_LAB_1 --compact
terraform scan results:
Passed checks: 7, Failed checks: 0, Skipped checks: 0
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
PASSED for resource: aws_security_group.admin
...
exit=0
Seven passes, including the group with SSH open to 0.0.0.0/0. This is the one to remember. The check ran, the output looks healthy, and it can never fail. We dumped conf from a throwaway check to confirm the shape; you should do the same once per resource type before trusting any field access.
Unwrapping the list but matching port 22 exactly. With rule.get("from_port", [None])[0] == 22 and rule.get("cidr_blocks", [[]])[0], the draft caught admin and nothing else. jump_legacy (ports 0 to 1024) passed, and the two standalone rule resources were never evaluated because supported_resources named only aws_security_group.
A YAML wildcard with not_contains. The YAML docs show ingress.*.cidr_blocks with contains as the way to find 0.0.0.0/0 in any block. A model then flips it to not_contains for the compliant condition:
attribute: "ingress.*.cidr_blocks"
operator: "not_contains"
value: "0.0.0.0/0"
$ ./check_policy.sh drafts/y2 CKV2_LAB_1 expected.txt
WRONG: CKV2_LAB_1
MISSED: aws_security_group.jump_legacy
NOT EVALUATED: aws_vpc_security_group_ingress_rule.batch_ssh
NOT EVALUATED: aws_security_group_rule.legacy_all
FALSE POSITIVE: aws_security_group.web
FALSE POSITIVE: aws_security_group.web_admin
NOT EVALUATED: aws_security_group_rule.legacy_egress
It flagged admin, but it also flagged public HTTPS, because the policy never mentions a port. The YAML docs also warn that not_contains over a wildcard can still evaluate true when another list element doesn't contain the value, and suggest not instead. On 3.4.14 with this fixture, admin (one bastion block, one open block) did fail, so we couldn't reproduce that warning here. Test the operator on your own fixture rather than trusting either the docs or our result.
A YAML not / and that can't keep blocks together. Following the docs' advice gives a better-looking policy:
definition:
not:
and:
- cond_type: "attribute"
resource_types:
- "aws_security_group"
attribute: "ingress.*.cidr_blocks"
operator: "contains"
value: "0.0.0.0/0"
- cond_type: "attribute"
resource_types:
- "aws_security_group"
attribute: "ingress.*.from_port"
operator: "less_than_or_equal"
value: 22
$ ./check_policy.sh drafts/y3 CKV2_LAB_1 expected.txt
WRONG: CKV2_LAB_1
MISSED: aws_security_group.jump_legacy
NOT EVALUATED: aws_vpc_security_group_ingress_rule.batch_ssh
NOT EVALUATED: aws_security_group_rule.legacy_all
FALSE POSITIVE: aws_security_group.web_admin
NOT EVALUATED: aws_security_group_rule.legacy_egress
web now passes, but web_admin fails: its 443 block supplies the 0.0.0.0/0 and its bastion block supplies the port 22. Each ingress.* wildcard is evaluated on its own, so the two conditions can match different blocks of the same resource. It also still only checks 0.0.0.0/0, so the office range in jump_legacy slips through.
We stopped iterating on YAML here. Each attribute condition matched across all blocks of a resource independently, so we couldn't find a way in this policy format to say "the same block." YAML is a good fit for single-attribute rules (a tag must exist, an argument must be within a list) and for connection rules such as "every load balancer is attached to a security group." For per-block logic with ranges and CIDR math, Python is the right format.
Step 5: The Python check that passed
from __future__ import annotations
import ipaddress
from typing import Any
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
BASTION = ipaddress.ip_network("10.20.0.0/24")
SSH_PORT = 22
def _first(conf: dict[str, Any], key: str, default: Any = None) -> Any:
"""Checkov wraps every Terraform attribute value in a list: {"from_port": [22]}."""
value = conf.get(key)
if isinstance(value, list):
return value[0] if value else default
return default if value is None else value
def _covers_ssh(protocol: Any, from_port: Any, to_port: Any) -> bool:
if str(protocol) in ("-1", "all"):
return True
if str(protocol) not in ("tcp", "6"):
return False
try:
return int(from_port) <= SSH_PORT <= int(to_port)
except (TypeError, ValueError):
return True # unresolved variable: fail closed so a human looks at it
def _outside_bastion(cidr: Any) -> bool:
try:
return not ipaddress.ip_network(str(cidr), strict=False).subnet_of(BASTION)
except (TypeError, ValueError):
return True # IPv6 or unresolved reference: not the bastion range
class SSHFromBastionOnly(BaseResourceCheck):
def __init__(self) -> None:
name = "Ensure SSH is only allowed from the bastion range"
id = "CKV_LAB_1"
supported_resources = (
"aws_security_group",
"aws_security_group_rule",
"aws_vpc_security_group_ingress_rule",
)
categories = (CheckCategories.NETWORKING,)
super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)
def scan_resource_conf(self, conf: dict[str, list[Any]]) -> CheckResult:
if self.entity_type == "aws_security_group":
rules = [r for r in conf.get("ingress", []) if isinstance(r, dict)]
sources = lambda r: (_first(r, "cidr_blocks", []) or []) + (_first(r, "ipv6_cidr_blocks", []) or [])
proto_key = "protocol"
elif self.entity_type == "aws_security_group_rule":
if _first(conf, "type") != "ingress":
return CheckResult.PASSED
rules = [conf]
sources = lambda r: (_first(r, "cidr_blocks", []) or []) + (_first(r, "ipv6_cidr_blocks", []) or [])
proto_key = "protocol"
else: # aws_vpc_security_group_ingress_rule
rules = [conf]
sources = lambda r: [c for c in (_first(r, "cidr_ipv4"), _first(r, "cidr_ipv6")) if c]
proto_key = "ip_protocol"
for rule in rules:
proto = _first(rule, proto_key)
if str(proto) in ("-1", "all"):
from_port, to_port = 0, 65535
else:
from_port, to_port = _first(rule, "from_port"), _first(rule, "to_port")
if not _covers_ssh(proto, from_port, to_port):
continue
bad = [c for c in sources(rule) if _outside_bastion(c)]
if bad:
self.details.append(f"tcp/22 reachable from {', '.join(map(str, bad))}")
return CheckResult.FAILED
return CheckResult.PASSED
check = SSHFromBastionOnly()
It checks each block on its own, treats port ranges and protocol -1 as covering 22, does real CIDR math with ipaddress, covers all three resource types, uses self.entity_type to tell them apart as the Python docs show, and reports the offending source with self.details:
$ checkov -d tf --external-checks-dir drafts/final -c CKV_LAB_1 --compact --quiet
terraform scan results:
Passed checks: 6, Failed checks: 4, Skipped checks: 0
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_security_group.admin
Details: tcp/22 reachable from 0.0.0.0/0
File: /main.tf:5-25
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_security_group.jump_legacy
Details: tcp/22 reachable from 198.51.100.0/24
File: /main.tf:28-39
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_vpc_security_group_ingress_rule.batch_ssh
Details: tcp/22 reachable from 0.0.0.0/0
File: /main.tf:48-54
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_security_group_rule.legacy_all
Details: tcp/22 reachable from 0.0.0.0/0
File: /main.tf:113-120
exit=1
$ ./check_policy.sh drafts/final CKV_LAB_1 expected.txt
OK: CKV_LAB_1 matched all 10 expected results
Variables. Real Terraform rarely hard-codes CIDRs. In tf-vars/, one group uses var.office_cidr with a default of 203.0.113.0/24, and one uses var.vendor_cidr with no default:
$ checkov -d tf-vars --external-checks-dir drafts/final -c CKV_LAB_1 --compact
terraform scan results:
Passed checks: 0, Failed checks: 2, Skipped checks: 0
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_security_group.from_default
Details: tcp/22 reachable from 203.0.113.0/24
File: /main.tf:10-20
Check: CKV_LAB_1: "Ensure SSH is only allowed from the bastion range"
FAILED for resource: aws_security_group.from_unset
Details: tcp/22 reachable from var.vendor_cidr
File: /main.tf:22-32
exit=1
Checkov replaced the variable with its default. The unset one reached the check as the literal string var.vendor_cidr, which isn't a valid network, so the check failed closed and named it. A draft that swallows the ValueError and passes would hide every unresolved source. Decide which way you want unknowns to go, and write it into the prompt.
Two more edge cases, in a third fixture: SSH from 10.20.0.64/26, a subnet inside the bastion range, passed, and SSH from ::/0 through ipv6_cidr_blocks failed with Details: tcp/22 reachable from ::/0. A string comparison against "10.20.0.0/24" would have got the first one wrong.
Common mistakes in LLM-written Checkov checks
| Mistake | What Checkov did (3.4.14) | Fix |
|---|---|---|
YAML operator that isn't in the list (not_in) | WARNI ... operator not_in is not supported. Skipping., exit 0 | Use the documented list (not_within, not_contains, ...) |
Invented enum (CheckCategories.NETWORK) | ERROR Cannot load external check, exit 0 | CheckCategories.NETWORKING; copy names from the docs |
No check = MyCheck() at the end | Nothing at all, exit 0 | Instantiate the class at module level |
conf["from_port"] == 22 | Ran and passed every resource | Unwrap: conf["from_port"][0]; cidr_blocks is [[...]] |
| Exact port match | Missed a 0–1024 range | from_port <= 22 <= to_port, plus protocol -1 |
Only aws_security_group in supported_resources | Standalone rules never evaluated | Add aws_vpc_security_group_ingress_rule and aws_security_group_rule |
| String compare on CIDRs | Can't tell a subnet of the bastion from a stranger | ipaddress and subnet_of |
| YAML wildcards for per-block logic | Matched across different blocks; false positive | Python, block by block |
| No port condition at all | Flagged public HTTPS | Put every part of the rule in the check |
| Unknowns pass silently | Unset variables would pass | Fail closed and report the value |
A small validator for the loop
Exit codes can't tell you whether a custom check ran, so the validator reads Checkov's JSON, keeps only your check ID, and compares it to the planted list. --soft-fail keeps Checkov's exit code out of the way so the script decides.
#!/bin/bash
# usage: check_policy.sh <checks-dir> <check-id> <expected.txt> [tf-dir]
# expected.txt lines: "FAILED <resource address>" or "PASSED <resource address>"
dir=$1; id=$2; expected=$3; tf=${4:-tf}
checkov -d "$tf" --external-checks-dir "$dir" -c "$id" -o json --soft-fail > out.json 2> err.log
python3 - "$id" "$expected" <<'PY'
import json, sys
check_id, expected_path = sys.argv[1], sys.argv[2]
raw = open("out.json").read().strip()
data = json.loads(raw) if raw else {}
got = {}
for report in (data if isinstance(data, list) else [data]):
results = report.get("results", {}) if isinstance(report, dict) else {}
for key, label in (("failed_checks", "FAILED"), ("passed_checks", "PASSED")):
for c in results.get(key, []):
if c["check_id"] == check_id:
got[c["resource"]] = label
if not got:
errors = sum(1 for line in open("err.log") if "[ERROR]" in line or "[WARNI]" in line)
print(f"NOT LOADED: {check_id} produced no results ({errors} warning/error lines in err.log)")
sys.exit(2)
problems = []
for line in open(expected_path):
if not line.strip():
continue
want, resource = line.split()
have = got.get(resource)
if have is None:
problems.append(f"NOT EVALUATED: {resource}")
elif want == "FAILED" and have == "PASSED":
problems.append(f"MISSED: {resource}")
elif want == "PASSED" and have == "FAILED":
problems.append(f"FALSE POSITIVE: {resource}")
if problems:
print(f"WRONG: {check_id}")
print("\n".join(problems))
sys.exit(1)
print(f"OK: {check_id} matched all {len(got)} expected results")
PY
Across all eight drafts:
y1 (not_in operator) NOT LOADED: CKV2_LAB_1 produced no results (8 warning/error lines in err.log)
y2 (not_contains) WRONG: 1 missed, 2 false positives, 3 not evaluated
y3 (not / and wildcards) WRONG: 1 missed, 1 false positive, 3 not evaluated
p1 (invented category) NOT LOADED: CKV_LAB_1 produced no results (20 warning/error lines in err.log)
p2 (list-wrapped values) WRONG: 2 missed, 3 not evaluated
p3 (exact port 22) WRONG: 1 missed, 3 not evaluated
p4 (no check instance) NOT LOADED: CKV_LAB_1 produced no results (0 warning/error lines in err.log)
final OK: CKV_LAB_1 matched all 10 expected results
The summary lines are condensed from the full output, which lists each resource as in Step 4. Note the last NOT LOADED line: zero warnings. A check that never registers leaves nothing in the log to grep for, which is why the validator tests for results, not for errors.
To close the loop with a model, send the NOT LOADED or WRONG lines back and ask for a corrected file. This sketch does that with the OpenAI Python SDK and RedRouter's https://redrouter.org/v1 base URL from the quickstart. We did not run it against the API for this post; the Checkov half is the script above.
import os, subprocess
from openai import OpenAI
client = OpenAI(base_url="https://redrouter.org/v1", api_key=os.environ["REDROUTER_API_KEY"])
messages = [{"role": "user", "content": open("prompt.txt").read()}] # Step 2 prompt
for attempt in range(4):
reply = client.chat.completions.create(model="glm-5.3-flash-red", messages=messages)
code = reply.choices[0].message.content.strip().removeprefix("```python").removesuffix("```").strip()
open("candidate/SSHFromBastionOnly.py", "w").write(code + "\n")
input("Review candidate/SSHFromBastionOnly.py. Press Enter to run it or Ctrl+C to stop. ")
check = subprocess.run(["./check_policy.sh", "candidate", "CKV_LAB_1", "expected.txt"], capture_output=True, text=True)
print(check.stdout.strip())
if check.returncode == 0:
break
messages += [{"role": "assistant", "content": code},
{"role": "user", "content": check.stdout.strip() + "\nReturn the corrected file only."}]
Read the file yourself before the loop runs it, every round. That's the subject of the next section.
Review LLM-written Python checks before Checkov runs them
A YAML policy is data. A Python check is code that Checkov imports and executes. The Python docs say so directly: by default, Checkov loads every .py file under --external-checks-dir and executes it. A model-written check runs with the same access as your CI job, including its cloud credentials and tokens. So:
- Read every generated
.pyfile before it runs, in the lab and in CI. Reject anything that importsos,subprocess,socketorrequests, or reads files. A check needsconfand nothing else. - Keep the custom-checks directory in review like any other code. Checkov 3.4.14 can also verify signatures: with
--external-checks-public-key, every.pyfile must end with a signed# checkov-digest:trailer, and Checkov exits with code 2 before scanning if any file fails, according to the Python custom policies docs. We confirmed the flag is incheckov --helpfor 3.4.14 but did not test signing. - Give each check file a unique name. The docs warn that if two policies share a file name, only the first one loads. That's another silent skip.
- In CI, run the validator against the fixture first, then scan the real code. A check that says
NOT LOADEDon the fixture should fail the pipeline.
Where this fits with other policy engines
Checkov reads Terraform and other infrastructure files before anything is deployed. If you enforce rules at admission time or over JSON input, OPA Rego policies with an LLM uses opa test as the first gate. If the rule is about application source rather than infrastructure, Semgrep rules with an LLM covers pattern rules tested against code you own, and LLM secure code review covers reviewing the code itself. The loop is the same in all of them: plant the answer, run the engine, diff.
What to send the model, and what not to
- Send: the Checkov version, the format you chose and why, the exact class and enum names, a dumped
confsample for each resource type, the rule in plain words with its edge cases (ranges,-1, IPv6, variables), the resource types to cover, and the exact Checkov message or validator line from the last round. - Scrub: account IDs, real CIDR ranges, hostnames, bucket names, ARNs and anything that came from a
.tfvarsfile. Replace them with documentation ranges such as198.51.100.0/24, as we did. - Don't send: state files or plan JSON from real accounts. HashiCorp's sensitive data guide notes that state and plan files can contain values such as database passwords or API tokens, and local state is a plaintext file. A model needs the shape of a resource, not your estate.
- Check retention. On RedRouter, account zero data retention is an opt-in setting, off by default. The data handling docs explain what is stored and the controls, and what RedRouter keeps covers the defaults in plain terms.
Choosing a model for Checkov policies
Any model that follows "return the file only" and fixes code from an error message will do; the validator does the judging. On RedRouter, GLM 5.3 Flash Red (glm-5.3-flash-red) is $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. red-cyber-1 (Beta), the featured model for authorized penetration testing and red-team work, is $0.28 / $0.13 / $1.10 per 1M tokens. Current rates for every model are in the models docs, and plans are on /pricing.
Policy prompts describe exposure plainly: SSH open to the internet, admin ports reachable from vendor ranges, rules that slip past a scanner. RedRouter is built for that kind of authorized security work.
FAQ
Can I write a Checkov policy with an LLM?
Yes, as a first draft. In our lab on Checkov 3.4.14, three of eight drafts never ran (an unsupported YAML operator, an invented category and a missing check = ... line), and all three exited 0. Four more ran and gave wrong results. Only the final Python check failed exactly the four planted resources and passed the other six.
How do I test an LLM Checkov custom check?
Run it alone with checkov -d <dir> --external-checks-dir <checks> -c <ID> against a fixture with planted violations, compliant resources and a near-miss. Confirm your check ID appears in the results, then diff the FAILED and PASSED resources against the list you wrote beforehand. The check_policy.sh script above does both.
What does an AI Terraform Checkov policy for SSH look like?
For "SSH only from the bastion," a Python check that extends BaseResourceCheck, covers aws_security_group, aws_security_group_rule and aws_vpc_security_group_ingress_rule, unwraps Checkov's list-wrapped values, treats port ranges and protocol -1 as covering 22, and compares CIDRs with ipaddress. The full file is in Step 5.
Why does my custom Checkov check not run?
In our runs: an operator that isn't supported (Checkov logs "Skipping"), an exception at import time (Checkov logs "Cannot load external check"), or no module-level instance (Checkov logs nothing). The docs add a fourth: two policy files with the same name, where only the first loads. In every case we saw, the exit code was 0.
Should I write Checkov policies in YAML or Python?
YAML for single-attribute rules, allow and deny lists, and connections between resources. Python when the rule has to look inside one nested block at a time, do arithmetic on ranges or parse CIDRs. Our SSH rule needed "the same block," and the YAML wildcard conditions matched across blocks.
Is it safe to paste Terraform into an LLM?
Paste the shape, not your estate. Send a scrubbed resource block and a dumped conf sample, never state files, plan JSON or .tfvars from real accounts. On RedRouter, account zero data retention is opt-in and off by default; see the data handling docs.
Sources
- Checkov documentation: What is Checkov, CLI command reference, Custom policies overview, Python custom policies, YAML custom policies, Terraform policy index.
- Checkov releases: checkov 3.4.14 on PyPI, GitHub release 3.4.14.
- Terraform: Manage sensitive data; AWS provider aws_security_group, aws_vpc_security_group_ingress_rule.
- Lab outputs: Checkov 3.4.14 from PyPI on Python 3.13, run against our own Terraform fixtures. No model was called.
- OpenAI Python SDK.
- RedRouter Docs: Quickstart, Models and pricing, Data handling.