Interview Prep/DevSecOps/Cloud Security, CIS and Compliance

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.

All DevSecOps questions Roadmap: Policy as code

More on Cloud Security, CIS and Compliance