Terraform · Infrastructure as code
How do you enforce policy as code for Terraform?
Short answer
Policy as code encodes guardrails such as required tags, approved regions and no public buckets. Evaluate the plan JSON in CI or use Sentinel in HCP Terraform, and treat exceptions as reviewed, time-bound decisions.
Policy as code turns organisational rules into executable checks. The plan JSON is the usual input because it shows the intended change before it happens. A policy can block a plan that creates a public bucket, uses an unapproved region or omits a required tag.
package terraform
deny contains msg if {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
resource.change.after.acl == "public-read"
msg := "S3 buckets must not be public"
}Tooling options
- OPA with conftest against terraform show -json output
- Sentinel inside HCP Terraform
- Checkov or tfsec for built-in security rules
- Cloud-native organisation policies as a complementary control
Start with a small set of high-value rules and test each policy against known-good and known-bad plans. Too many blocking rules push teams to bypass the pipeline. Use advisory mode first, measure false positives, then promote rules to blocking with a documented exception process.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What input does a plan-based policy evaluate?
- 2How do you roll out a new blocking policy safely?
- 3What is the difference between Sentinel and OPA?
- 4Why are cloud-native guardrails still needed?
Say it in the interview
I enforce policy against the plan JSON, so violations are caught before apply. A small set of high-value rules covers required tags, approved regions and public access, and I test each rule against good and bad plans. I roll out in advisory mode first, then make rules blocking with a documented exception path. Policy checks complement cloud guardrails; they do not replace IAM or SCPs.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.