Infrastructure as Code promised us repeatability, but without automated testing it only gives us repeatable mistakes. I've seen teams with beautifully structured Terraform repositories push a single variable change that exposed an RDS instance to the public internet for three weeks because no automated check caught it. terraform validate passed, terraform plan looked fine at a glance, and code review missed the missing publicly_accessible = false. This article is about closing that gap with a layered validation strategy. We will implement real integration tests with Terratest, static security scanning with Checkov, and enforceable governance with Policy-as-Code using OPA/Conftest. In my experience, none of these tools alone is sufficient; the value comes from orchestrating them at different stages of your delivery pipeline.
Beyond terraform validate: Why Static Syntax Checks Miss Critical Failure Modes
The default Terraform toolchain gives you a false sense of security. terraform fmt -check ensures formatting, terraform validate confirms HCL syntax and internal consistency, and tflint adds provider-specific linting. What none of them do is answer the question: will this actually work when deployed, and does it comply with our security posture?
I categorize infrastructure defects into three failure classes that require different testing approaches. First, syntactic defects: typos, invalid resource arguments, missing required fields. These are caught early. Second, semantic and integration defects: a security group that allows 0.0.0.0/0 on port 22, a subnet without a NAT gateway that prevents private instances from pulling images, an IAM policy with excessive permissions that still passes validation. Third, compliance defects: deploying a resource in an unapproved region, failing to tag resources with CostCenter, or using an unencrypted S3 bucket.
The Terraform Documentation is clear that validate is a static check and does not access remote state or provider APIs. This means it cannot verify that an AMI ID exists in the target region, that you have quota for the instance type, or that a referenced VPC actually exists. In one project, we had a module that created an EKS cluster. Validate passed, but apply failed after 12 minutes because the IAM role lacked eks:CreateCluster. That feedback loop is too slow and too expensive for a CI pipeline.
Mapping Validation Layers to the Delivery Lifecycle
The most effective model I've found mirrors application testing: unit, integration, and contract/policy tests. Static analysis (Checkov, tflint) acts as your unit test - fast, cheap, no infrastructure required. Terratest provides integration testing - it deploys real infrastructure, asserts on outputs and API responses, then tears it down. Policy-as-Code sits as a contract test that gates any deployment regardless of how it was authored. Trying to use one tool for all three layers always leads to gaps. For example, you can write a Checkov check for "S3 bucket must have encryption," but you cannot use Checkov to verify that your application can actually write to that bucket after deployment. That requires Terratest.
Terratest in Practice: Spinning Ephemeral Environments for True Integration Assurance
Terratest is a Go library from Gruntwork that wraps Terraform and provides helpers for testing infrastructure. It is not a linter; it actually runs terraform init, apply, validates with AWS SDK, GCP SDK, Azure SDK or HTTP calls, and then runs destroy. This is powerful and, if misused, extremely dangerous to your AWS bill.
The key pattern is to use isolated, ephemeral environments per test run. I've found that running Terratest against a long-lived shared environment defeats the purpose and creates flaky tests due to state contention and drift. Instead, every test invocation should generate a unique namespace using a random string and deploy into it.
Your repository structure matters. When you follow solid patterns for Terraform Modules: Design Patterns, Versioning and Registry Publishing, Terratest becomes much easier to implement. Test the module in isolation in modules/vpc, not the root composition that deploys your entire production stack. Keep tests in test/ adjacent to the module.
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/stretchr/testify/assert"
)
func TestVpcModuleCreatesPrivateSubnets(t *testing.T) {
t.Parallel()
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../modules/vpc",
Vars: map[string]interface{}{
"cidr_block": "10.10.0.0/16",
"az_count": 3,
"enable_nat_gateway": true,
"environment": "test",
},
EnvVars: map[string]string{
"AWS_DEFAULT_REGION": "us-east-1",
},
})
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
vpcID := terraform.Output(t, terraformOptions, "vpc_id")
privateSubnetIDs := terraform.OutputList(t, terraformOptions, "private_subnet_ids")
assert.Len(t, privateSubnetIDs, 3)
// Validate via AWS API that subnets are actually private (no public IP on launch)
for _, subnetID := range privateSubnetIDs {
subnet := aws.GetSubnetById(t, subnetID, "us-east-1")
assert.False(t, *subnet.MapPublicIpOnLaunch, "private subnet should not auto-assign public IPs")
}
// Verify NAT gateways exist and are available
natGateways := aws.GetNatGatewaysForVpc(t, vpcID, "us-east-1")
assert.Len(t, natGateways, 3)
}
Several operational details make this reliable at scale. First, always set t.Parallel() and use terraform.WithDefaultRetryableErrors to handle transient AWS throttling. Second, use a wrapper like cloud-nuke or a scheduled Lambda to clean up orphaned resources when a test run is interrupted and defer terraform.Destroy never executes. I recommend tagging every test resource with terratest=true and ttl=3h. Third, isolate state. Do not use your production S3 backend for tests. Use local state or a dedicated test backend with locking disabled, or a key prefix like key = "test/vpc/${random_id}/terraform.tfstate". Issues around state file locking and remote backends are covered in depth in Terraform State Management: Remote Backends, Locking and State Migration, and the same principles apply to keep test isolation strict.
Controlling Cost and Execution Time
Terratest tests are slow. A VPC test might take 3 minutes, an EKS cluster test 18-22 minutes. You cannot run the full suite on every commit. In my pipelines, I run fast static checks on every pull request and trigger the full Terratest suite only on merges to main or nightly schedules. Use Terratest's terraform.Options with RetryableTerraformErrors and stages to split plan/apply/validate so you can reuse deployed infrastructure for multiple assertions without redeploying.
Checkov Under the Hood: From Out-of-the-Box Rules to Custom Python Framework Checks
Checkov by Bridgecrew scans IaC for misconfigurations using a graph-based analysis of Terraform, CloudFormation, Kubernetes manifests, and Dockerfile. Out of the box it ships with 1000+ policies like CKV_AWS_20 (S3 bucket public ACL) or CKV_AWS_23 (RDS encryption). Running it is trivial, but tuning it for your organization is where the real work starts.
# .checkov.yaml - checked into repo root
directory:
- .
framework:
- terraform
soft-fail: false
skip-check:
- CKV_AWS_19 # We handle S3 encryption via default bucket policy at org level
compact: true
quiet: true
# Enforce custom policy directory
external-checks-dir:
- ./checks/custom
The default checks are noisy. In my experience, about 15% of failures in a greenfield repo are legitimate blockers, 30% are acceptable risks with justification, and the rest is noise that causes alert fatigue. You must curate. Use skip-check with a comment explaining why, and enforce that every skip has a ticket. Better, use Checkov's baseline feature checkov --create-baseline to acknowledge existing debt while blocking new violations.
Authoring Custom Checks When Defaults Are Not Enough
Checkov's real power for advanced teams is custom checks. You can write them in Python or YAML. For example, our organization requires every resource to have tags = { CostCenter, Environment, Owner }. No built-in check enforces that across all resource types.
# checks/custom/RequireCostCenterTag.yaml
metadata:
name: "Ensure all resources have CostCenter tag"
id: "CUSTOM_AWS_001"
category: "GENERAL_SECURITY"
definition:
cond_type: "attribute"
resource_types: "all"
attribute: "tags.CostCenter"
operator: "exists"
value: "true"
For more complex logic, use Python. I once wrote a check that failed any aws_security_group_rule where cidr_blocks contained 0.0.0.0/0 and from_port was between 22-3389, but allowed it if the description contained [approved-exception] with a Jira ticket pattern. Python checks let you inspect multiple attributes and use regex. Place them in your external-checks-dir and they run alongside built-in policies. Run Checkov with --framework terraform --output sarif to produce SARIF for GitHub Advanced Security ingestion, which gives you inline PR annotations.
Writing Enforceable Policy-as-Code with OPA, Conftest, and Sentinel
Checkov tells you what's wrong; Policy-as-Code prevents it from being deployed. Open Policy Agent (OPA) and its companion Conftest evaluate the Terraform plan JSON against Rego policies. Unlike Checkov which scans HCL statically, OPA evaluates the fully rendered plan, including module expansion and variable interpolation. This catches violations that only appear after terraform plan.
HashiCorp Sentinel is the analogous tool for Terraform Cloud/Enterprise. If you are on Terraform Cloud, use Sentinel. If you are on open-source Terraform or want provider-agnostic policies, use OPA/Conftest. I prefer Conftest for most teams because Rego policies can be reused for Kubernetes admission control and CI gating.
The workflow is: terraform plan -out plan.binary && terraform show -json plan.binary > plan.json && conftest test plan.json. Your Rego policy operates on the plan JSON structure under input.planned_values.root_module.resources.
package main
# Deny S3 buckets without server-side encryption
deny[msg] {
resource := input.planned_values.root_module.resources[_]
resource.type == "aws_s3_bucket"
not resource.values.server_side_encryption_configuration
msg := sprintf("S3 bucket '%s' must have server_side_encryption_configuration", [resource.address])
}
# Deny any resource without required tags
deny[msg] {
resource := input.planned_values.root_module.resources[_]
resource.type != "aws_iam_policy" # IAM resources don't support tags
tags := resource.values.tags
not tags.CostCenter
msg := sprintf("Resource '%s' is missing required tag CostCenter", [resource.address])
}
# Deny deployment outside approved regions
deny[msg] {
resource := input.planned_values.root_module.resources[_]
resource.values.region
not resource.values.region in {"us-east-1", "us-west-2", "eu-west-1"}
msg := sprintf("Resource '%s' uses unapproved region '%s'", [resource.address, resource.values.region])
}
Keep policies in a dedicated policy/ repository and version them. Conftest supports pulling policies via conftest pull from an OCI registry, which lets you distribute the same policies to multiple repositories. I've found that starting with warn rules and promoting them to deny after a two-week notification period prevents teams from being blocked overnight by a new governance rule.
Testing Your Policies
Rego policies themselves need tests. OPA includes opa test. Write unit tests for each deny rule with both positive and negative plan JSON fixtures. Without this, you will ship a policy that blocks all deploys due to a typo in the Rego syntax, which is worse than no policy at all.
Stitching Validation Layers into a CI/CD Pipeline That Actually Blocks Bad Deploys
Tooling is useless if the pipeline does not enforce it. The layered pipeline I run for production Terraform looks like this: pre-commit hooks, PR checks, and post-plan gating.
On developer workstations, pre-commit runs terraform fmt, tflint, and checkov --compact in under 10 seconds. This gives fast feedback. In CI on pull request, we run a second Checkov scan with SARIF output, terraform validate, and conftest test against the plan JSON. This stage must be blocking. If Checkov or Conftest fails, the PR cannot be merged.
Terratest runs on merge to main against a sandbox account that mirrors production. It does not run on every PR due to cost and time. The pipeline posts results back to the PR as a status check and uploads the JUnit XML from go test -json. I use GitHub Actions with OIDC federation to AWS, so no long-lived credentials are stored. The workflow assumes a role with permissions scoped to the sandbox account only.
For teams practicing GitOps with ArgoCD and Flux: Declarative Kubernetes Deployment, the same policy layer applies. Conftest can validate Helm charts and Kubernetes manifests before ArgoCD syncs them. We run conftest test against the rendered manifests in CI, so a non-compliant manifest never reaches the GitOps repo.
| Validation Layer | Tool | Execution Stage | Speed & Cost | What It Catches |
|---|---|---|---|---|
| Static Security & Linting | Checkov, tflint | Pre-commit & PR | Seconds, free | Misconfigurations, missing encryption, open SGs, tag violations |
| Policy Gating on Plan | OPA/Conftest, Sentinel | PR - after terraform plan | Seconds, free | Governance violations, region restrictions, approved module usage |
| Integration Testing | Terratest (Go) | Merge to main / Nightly | Minutes to hours, incurs cloud cost | Runtime failures, IAM permission gaps, networking reachability, output correctness |
| Drift & Compliance Scan | Checkov drift, terraform plan -detailed-exitcode | Scheduled (hourly/daily) | Minutes, read-only API calls | Manual console changes, state drift, policy regression |
The table illustrates why you need all layers. Checkov is fast but cannot prove an EKS cluster actually becomes active. Terratest proves runtime behavior but is too slow to run on every commit. OPA gates based on the final plan, including values computed by modules, which Checkov cannot see.
Handling Policy Drift, Module Updates, and State Inconsistencies in Long-Lived Environments
Policies rot. Modules evolve. State drifts. Your validation pipeline must account for all three. When you publish a new version of a shared VPC module, existing live environments drift from the desired policy. I schedule a nightly drift detection job that runs terraform plan -detailed-exitcode and checkov --framework terraform_plan against the current state file in read-only mode. If exit code 2 is returned (diff detected), we alert on Slack and open a Jira ticket.
For Checkov and OPA, pin versions. A Checkov upgrade from 2.x to 3.x can introduce 50 new checks and break every pipeline. Pin the version in your Dockerfile or GitHub Action: bridgecrew/checkov:3.1.20. For OPA policies, tag releases in your policy repo and have consuming repos reference a specific tag: conftest pull oci://ghcr.io/org/policies:v1.4.0. This lets you roll out new denies progressively.
State inconsistencies are especially painful for Terratest. If a previous test failed to destroy resources due to a timeout, the next run may fail with ResourceAlreadyExists. Build idempotency into your tests: generate a unique suffix per run with random_id or random_pet, and make your Terratest Vars override that suffix. Also, treat state backend configuration as code and test it. A misconfigured S3 backend with versioning disabled can silently corrupt state during parallel applies.
Finally, log every policy decision. I ship conftest and Checkov JSON output to S3 and index it in our SIEM. When an auditor asks why a resource was allowed in 2024 but denied in 2025, we can show the exact policy version and plan that was evaluated. That audit trail is as important as the block itself.
Frequently Asked Questions
Should I use Checkov or OPA/Conftest if I can only pick one?
Pick Checkov if you need immediate, low-effort scanning with broad coverage. Its out-of-the-box rules catch 80% of common misconfigurations without writing Rego. Choose OPA/Conftest if you need custom governance that is provider-agnostic and enforced on the rendered plan JSON, such as restricting regions, requiring specific module sources, or integrating the same policies with Kubernetes admission controllers. Most mature teams run both: Checkov as a fast linter and OPA as a hard gate.
How do I prevent Terratest from becoming prohibitively expensive?
Run Terratest against the smallest viable infrastructure. Test modules in isolation, not full environments. Use t.Parallel() to shorten wall-clock time but limit concurrency to avoid API throttling. Deploy the cheapest instance types (t3.micro) and use short TTL tags with automated cleanup via a Lambda that nukes resources older than 3 hours. Execute the full Terratest suite only on merge to main or nightly, not on every pull request, and keep fast Checkov/OPA checks on every PR.
Can Checkov and Conftest evaluate Terraform modules from the private registry?
Yes, but they need the expanded plan. Checkov scans HCL directly and will follow local modules, but for registry modules it evaluates the calling code only. Conftest evaluates terraform show -json plan.json, which already has all modules expanded and variables resolved, so it sees the final resource graph regardless of source. For that reason, always run terraform init before Checkov if you use registry modules, and use the plan JSON path for OPA.
How do I handle legitimate exceptions to policy-as-code rules?
Implement an allowlist mechanism with expiration. For Checkov, use inline skip comments with a required ticket reference: # checkov:skip=CKV_AWS_20: ticket SEC-1245 expires 2025-12-01 and have a scheduled linter that fails if the expiration date passes. For OPA, add a data-driven exception list where resources annotated with exception_policy = "approved:SEC-1245" are permitted, and validate that the ticket exists and is approved via an external data source. Never allow indefinite exceptions.