In this lesson, you will learn how to shift infrastructure governance "left" by programmatically blocking Terraform deployments that fail to meet your organization’s compliance, cost, or security mandates.
Moving Beyond Manual Oversight
In previous lessons, we covered how to modularize infrastructure and orchestrate deployments via CI/CD. However, relying on manual code reviews to catch misconfigurations—like an unencrypted S3 bucket or a production database without backup tags—is error-prone and unscalable. "Policy as Code" (PaC) allows you to define organizational requirements as machine-readable rules that automatically evaluate your Terraform execution plans before any resources are provisioned.
Integrating Policies into the Workflow
By utilizing a policy engine (like Open Policy Agent or Sentinel), you can inject a validation gate directly into your CI pipeline. When a developer runs terraform plan, the output is converted into JSON and evaluated against your defined policies. If the plan violates a rule, the engine returns an error and prevents the terraform apply step from executing.
For example, if you want to ensure all data infrastructure resources include a cost-center tag to support your FinOps-driven performance retrospectives, you would define a policy snippet like this:
# OPA/Rego example policy
package terraform.analysis
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not resource.change.after.tags["cost-center"]
msg := "S3 buckets must have a 'cost-center' tag for financial attribution."
}
The Power of Automated Guardrails
This approach transforms governance from a bureaucratic "gatekeeper" process into a continuous feedback loop. Developers receive immediate, automated feedback during their pull request process, teaching them the organization's standards as they work. Because the infrastructure code itself acts as the source of truth, you ensure that no "shadow" infrastructure can bypass your cost-attribution or security requirements, regardless of which team is deploying the resources.
Key Takeaway: Policy as Code serves as an automated programmatic gatekeeper, ensuring that infrastructure deployments align with security and financial standards before a single resource is actually provisioned.