How do you apply policy as code to a Terraform plan with Conftest?
AdvancedConceptCloud Security, CIS and Compliance
Answer
Conftest runs OPA Rego policies against structured files. Convert the plan to JSON and test it in CI before apply:
terraform plan -out tf.plan && terraform show -json tf.plan > plan.json
conftest test plan.json -p policy/
package main
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_security_group_rule"
rc.change.after.cidr_blocks[_] == "0.0.0.0/0"
rc.change.after.from_port <= 22
rc.change.after.to_port >= 22
msg := sprintf("%s opens SSH to the internet", [rc.address])
}
Unlike fixed-rule scanners, this encodes organisation-specific rules (required tags, approved instance families, allowed regions) in the same language we use for Kubernetes admission.
More on Cloud Security, CIS and Compliance
What is the cloud shared responsibility model?BeginnerWhat is CSPM?BeginnerWhat are CIS Benchmarks, and what is Level 1 vs Level 2?BeginnerHow do you run a CIS assessment of an AWS account with Prowler?IntermediateName the main AWS security services and what each does.BeginnerWhat should you know about CloudTrail configuration?Intermediate