Implementing Policy as Code with Terraform
Implementing Policy as Code with Terraform
Policy as Code transforms security and compliance requirements from documents into executable code that automatically validates Terraform configurations. This approach ensures consistent security standards across all infrastructure deployments while providing immediate feedback to developers. Policy as Code tools evaluate Terraform plans against organizational policies before allowing deployments.
Open Policy Agent (OPA) has become the standard for Policy as Code implementation with Terraform. OPA policies written in Rego language can enforce any security requirement, from simple resource tagging to complex network isolation rules. Organizations can create custom policies matching their specific security requirements and compliance obligations.
# Example OPA policy for Terraform security
package terraform.security
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
resource.change.after.acl == "public-read"
msg := sprintf("S3 bucket %s should not be publicly readable", [resource.address])
}
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
resource.change.after.publicly_accessible == true
msg := sprintf("Database %s should not be publicly accessible", [resource.address])
}
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_instance"
not resource.change.after.monitoring
msg := sprintf("EC2 instance %s must have monitoring enabled", [resource.address])
}
Sentinel, HashiCorp's policy as code framework, integrates natively with Terraform Enterprise and Terraform Cloud. Sentinel policies can enforce security requirements at different enforcement levels – advisory, soft mandatory, and hard mandatory. This graduated approach allows organizations to introduce new policies gradually while maintaining deployment flexibility for legitimate exceptions.