IaC Beyond Terraform - Testing Infrastructure as Code
1. Infrastructure Code Breaks Too
In the previous two articles of this series, we looked at OpenTofu as an alternative for provisioning infrastructure and Ansible for configuring it once created. But there’s a question that hangs over any of these flows: how do you know, before running apply in production, that a Terraform module won’t open a port it shouldn’t, destroy a resource by mistake, or simply have a syntax error? Testing infrastructure as code is as important as testing any other software — except that, unlike a pure function, the “side effects” of a badly written test here can be an unexpected cloud bill or a production service going down.
This article wraps up the series by covering three complementary layers of testing: static analysis with tflint, security and compliance checks with checkov, and real integration tests with Terratest.
2. The Testing Layers in IaC
It helps to think of these tools as layers that run at different moments in the code’s lifecycle, from the fastest/cheapest to the slowest/most expensive:
- Lint and static analysis (tflint): runs in seconds, with no cloud credentials and no need to run
terraform plan. It catches syntax errors, bad practices and provider-specific problems. - Security and compliance analysis (checkov): also static, but focused on identifying insecure configurations (public bucket, encryption disabled, security group open to
0.0.0.0/0) by comparing the code against a catalog of policies. - Integration tests (Terratest): the layer closest to reality — it actually runs
terraform applyin an isolated environment, validates the result, and then runsterraform destroy. Slower and more expensive (it uses real cloud resources), but it’s the only way to guarantee the module really works end to end.
A mature CI/CD pipeline runs all three, in that order, failing fast on the cheaper layers before reaching the more expensive ones.
3. tflint in Practice
tflint focuses on problems that terraform validate doesn’t catch, because validate only ensures the HCL syntax and types are correct — not that the use of a specific resource makes sense for that provider.
# Installation (Linux/macOS via the official script)
curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | bash
# Run it in the module directory
tflint --init # download the provider plugin (e.g. AWS)
tflint
An example configuration enabling the AWS plugin, which brings specific rules (invalid instance types, use of deprecated AMIs, etc.):
# .tflint.hcl
plugin "aws" {
enabled = true
version = "0.31.0"
source = "github.com/terraform-linters/tflint-ruleset-aws"
}
rule "terraform_deprecated_interpolation" {
enabled = true
}
rule "terraform_unused_declarations" {
enabled = true
}
With this, tflint flags things like variables that are declared and never used, or an instance_type that doesn’t exist on AWS — errors that, without this upfront check, would only show up in production at apply time.
4. checkov in Practice
checkov (from Bridgecrew/Prisma Cloud) analyzes Terraform code against hundreds of ready-made security and compliance policies (CIS Benchmarks, PCI-DSS, HIPAA, among others), without applying anything:
pip install checkov
checkov -d ./terraform
An example of a resource with an obvious security problem:
resource "aws_s3_bucket" "data" {
bucket = "my-company-data"
}
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
Running checkov against this file reports a failure for policy CKV_AWS_53 (“Ensure S3 bucket has block public ACLs enabled”), with the line number and an explanation of the risk. You can suppress a rule for a specific case when the exception is intentional and documented:
resource "aws_s3_bucket_public_access_block" "data" {
# checkov:skip=CKV_AWS_53:bucket for the site's public assets, intentional
bucket = aws_s3_bucket.data.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
This documents the exception right in the code, instead of invisibly silencing the alert somewhere in the pipeline.
5. Terratest in Practice
Terratest is a Go library (maintained by Gruntwork) for writing real integration tests against Terraform code. The typical test pattern is: apply → validate → destroy, always in a disposable environment.
// test/webserver_test.go
package test
import (
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/http-helper"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestWebServerModule(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../examples/webserver",
Vars: map[string]interface{}{
"environment": "test",
},
}
// Make sure 'terraform destroy' runs at the end,
// even if the test fails halfway through.
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
publicIP := terraform.Output(t, terraformOptions, "public_ip")
url := "http://" + publicIP
http_helper.HttpGetWithRetry(
t,
url,
nil,
200,
"Welcome",
30, // attempts
5*time.Second, // interval between attempts
)
assert.NotEmpty(t, publicIP, "the public_ip output should not be empty")
}
Running it:
cd test
go test -v -timeout 30m
The defer terraform.Destroy(...) right after creating the options is the most important detail of this pattern: it guarantees destroy runs even if one of the validations (HttpGetWithRetry, assert) fails mid-test, avoiding orphaned real cloud resources that generate unnecessary cost.
6. Putting It All Together in a CI/CD Pipeline
# .github/workflows/terraform-test.yml
name: Terraform Test Pipeline
on:
pull_request:
paths:
- "terraform/**"
jobs:
static-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: tflint
uses: terraform-linters/setup-tflint@v4
- run: tflint --init && tflint --chdir=terraform
- name: checkov
uses: bridgecrewio/checkov-action@master
with:
directory: terraform
integration-tests:
needs: static-checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.22"
- name: Terratest
working-directory: test
run: go test -v -timeout 30m
The integration-tests job only runs after static-checks passes — failing fast on the static checks (seconds) avoids spending time and money running real apply/destroy (minutes) for code that already had an obvious lint or security problem.
7. Avoiding Drift in Production
Automated tests keep broken code from reaching production, but they don’t prevent drift — a divergence between what the Terraform state says exists and what actually exists in the cloud (someone changed something by hand in the console, for example). For that, the recommended practice is to run terraform plan (or tofu plan) periodically against the production environment, outside the deploy flow, and alert if there’s a difference:
# Run by a cron/scheduled job, not by a deploy
terraform plan -detailed-exitcode
# exit code 0 = no changes, 1 = error, 2 = there are differences (drift)
-detailed-exitcode is what makes this automatable: a pipeline can check the exit code and raise an alert only when the value is 2, without having to parse the plan’s text output.
8. Series Conclusion
We wrap up this three-article series having gone beyond pure Terraform: OpenTofu as a provisioning alternative born out of a licensing crisis, Ansible covering the configuration of what’s already been provisioned, and now the three testing layers — tflint, checkov and Terratest — that give you confidence infrastructure code does exactly what it should before reaching production. None of these tools replaces Terraform; they all expand what’s possible around it, and it’s this combination — provision, configure and test — that underpins a truly reliable IaC pipeline.
References: