Infrastructure as Code FAQ: Top Questions
10. Using Sentinel or OPA for Policy as Code in Terraform
Policy as Code allows organizations to enforce security, compliance, and governance rules programmatically in their infrastructure workflows. Sentinel (HashiCorp) and Open Policy Agent (OPA) are two widely-used tools for this purpose in Terraform environments.
πΊοΈ Step-by-Step Instructions:
- Choose Sentinel (built into Terraform Cloud/Enterprise) or OPA (open source and flexible).
- Define policies in HCL (for Sentinel) or Rego (for OPA).
- Attach Sentinel policies to workspaces in Terraform Cloud under policy sets.
- For OPA, integrate it with CI/CD or wrapper scripts to enforce policies before
terraform apply
.
π₯ Example Input:
// Sentinel policy: require specific tags
import "tfplan"
main = rule {
all tfplan.resources as _, res {
all res.instances as inst {
"Environment" in inst.applied.tags
}
}
}
π Expected Output:
Terraform plan is blocked if a required tag like "Environment" is missing.
π Detailed Explanation:
- Sentinel: First-class integration with Terraform Cloud and Enterprise. Used for mandatory controls and soft-mandates.
- OPA: Open source, highly flexible. Integrates with many CI tools and Kubernetes. Language used is Rego.
- Policy Types:
advisory
β warns but does not blocksoft-mandatory
β blocks but allows overridehard-mandatory
β strictly enforced
- Benefits: Prevents misconfiguration, enforces standards, reduces manual review overhead.
π οΈ Use Cases:
- Ensuring all infrastructure is tagged correctly for cost and ownership tracking.
- Blocking public S3 buckets or open security groups.
- Restricting use of non-compliant instance types.
- Auditing and enforcing team-specific governance rules.