Terraform Advanced — Checkov, Conftest & OPA
Enforce organizational policies against Terraform plans and code.
Checkov
pip install checkov
# Scan HCL files
checkov -d .
# Scan a plan file
terraform plan -out=plan.tfplan
terraform show -json plan.tfplan > plan.json
checkov -f plan.json
Custom Checkov Policy (Python)
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckResult, CheckCategories
class S3BucketEncryption(BaseResourceCheck):
def __init__(self):
name = "Ensure S3 bucket has encryption"
id = "CUSTOM_001"
supported_resources = ["aws_s3_bucket"]
categories = [CheckCategories.ENCRYPTION]
super().__init__(name=name, id=id, categories=categories,
supported_resources=supported_resources)
def scan_resource_conf(self, conf):
# Check logic here
return CheckResult.PASSED
Conftest + OPA
Write policies in Rego:
# Install
brew install conftest
# Create policy
mkdir -p policy/
# policy/s3.rego
package main
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not resource.change.after.versioning[0].enabled
msg := sprintf("S3 bucket %s must have versioning enabled", [resource.name])
}
# Test against plan
terraform show -json plan.tfplan | conftest test -
Tool Comparison
| Tool | Language | Best For |
|---|---|---|
| Checkov | Python | 1000+ built-in rules, quick start |
| Conftest/OPA | Rego | Custom org policies, flexible |
| Sentinel | Sentinel | Terraform Cloud/Enterprise |
What’s Next?
Practice testing strategies.