Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Choose Sentinel (built into Terraform Cloud/Enterprise) or OPA (open source and flexible).
  2. Define policies in HCL (for Sentinel) or Rego (for OPA).
  3. Attach Sentinel policies to workspaces in Terraform Cloud under policy sets.
  4. 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 block
    • soft-mandatory – blocks but allows override
    • hard-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.