Policy Enforcement in Terraform with Open Policy Agent
The Terraform plan ran, but something felt wrong. Infrastructure was about to change, and no one had verified the rules. This is where Open Policy Agent (OPA) steps in.
OPA is a policy engine that checks configurations before they deploy. With Terraform, it becomes a guardrail. You write policies in Rego, OPA’s declarative language, and run them against Terraform plans. Every resource, every variable, every parameter — verified before apply.
Integrating OPA with Terraform starts with exporting your plan as JSON. Terraform’s terraform show -json command produces output that OPA can read. You point OPA to this file and match it against custom rules. For example: ensure all S3 buckets have encryption, block public IPs, enforce naming conventions. These rules run locally, in CI/CD pipelines, or in cloud-native workflows.
The benefit is control. No more relying on human review for every change. OPA policies are versioned alongside code. Terraform modules remain flexible, but enforcement stays consistent. Teams can add rules over time, adapting to new security or compliance needs without refactoring infrastructure.
Best practices:
- Keep Rego policies readable and modular.
- Store them in the same repo as Terraform code.
- Run OPA checks before merging pull requests.
- Use a CI job to fail builds that break policy.
This approach scales. Hundreds of resources, dozens of modules — same rules, enforced everywhere. OPA with Terraform closes the gap between intent and execution.
Build faster without losing control. Test it with your own Terraform stack today on hoop.dev and see live policy enforcement in minutes.