Cloud & DevOps
Infrastructure as Code Testing: Unit, Contract, and Policy-as-Code with Open Policy Agent (OPA)
Deploying misconfigured cloud infrastructure into production environments remains the leading source of enterprise security breaches and outage events. While application code routinely passes through rigorous unit and integration testing pipelines, Infrastructure as Code (IaC) has historically lacked equivalent automated verification. Establishing a production IaC testing pipeline combines static analysis, policy-as-code validation via Open Policy Agent (OPA) and Conftest, and real-world integration testing with Terratest.
The IaC Testing Pyramid: From Static Linting to Real Ephemeral Deployments
A comprehensive IaC validation strategy executes multiple verification gates before code review approval and cloud provisioning:
| Test Layer | Execution Phase | Tooling | Feedback Time |
|---|---|---|---|
| Linting & Formatting | Pre-commit hook / Pull Request | tflint, terraform fmt | < 5 seconds |
| Policy as Code (Static) | CI Pull Request (Plan Evaluation) | OPA, Conftest, Checkov | 10โ30 seconds |
| Integration / Contract | Nightly / Staging Pipelines | Terratest (Go), LocalStack | 3โ15 minutes |
Policy-as-Code with Rego: Mandatory S3 Encryption & Tagging
Below is a production Rego policy enforced via Conftest on Terraform JSON plan outputs, guaranteeing all provisioned S3 buckets enforce SSE-KMS encryption and enterprise cost-center tagging:
# policy/s3_compliance.rego
package main
# Deny unencrypted S3 buckets
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not has_encryption(resource)
msg := sprintf("S3 Bucket '%v' must have server-side encryption enabled", [resource.address])
}
has_encryption(resource) {
resource.change.after.server_side_encryption_configuration[_].rule[_].apply_server_side_encryption_by_default[_].sse_algorithm == "aws:kms"
}
# Deny buckets missing required FinOps governance tags
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
tags := resource.change.after.tags
not tags["CostCenter"]
msg := sprintf("Resource '%v' is missing mandatory tag 'CostCenter'", [resource.address])
}
Automated Ephemeral Integration Testing with Terratest
Terratest validates that modules actually provision correctly in cloud sandboxes by spinning up ephemeral test environments, executing assertions, and running terraform destroy automatically:
// test/vpc_module_test.go
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestVpcModule(t *testing.T) {
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../modules/vpc",
Vars: map[string]interface{}{
"environment": "terratest-ci",
"cidr_block": "10.200.0.0/16",
},
})
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
vpcId := terraform.Output(t, terraformOptions, "vpc_id")
assert.NotEmpty(t, vpcId)
}
- Shift-Left Compliance: Evaluating Rego policies directly against
terraform show -json tfplandetects non-compliant infrastructure prior to applying cloud changes. - Drift Prevention: Pair CI policy gates with scheduled read-only terraform plans to detect untracked manual modifications made via cloud consoles.
- Fast Failure Feedback: Run fast OPA checks before expensive cloud integration tests to conserve CI runner compute budgets.
