Testing Terraform with terraform test, check blocks and tflint
Unit tests for a Terraform module that need no AWS account: terraform test with mock_provider, validation and preconditions, a check block, tflint with the AWS ruleset, and a GitHub Actions job that runs them on every pull request.
For a long time my only "test" for Terraform was running plan and reading it. That works when you're the only person changing the code and you remember what every variable is for. It stops working the moment a module gets used in two places, or someone changes a default without knowing why it was set.
In this blog we will look at testing a small module properly, without an AWS account and without spending a rupee. We will use terraform test with a mocked AWS provider, variable validation, a precondition, a check block, and tflint. Then we wire all of it into CI. This one is advanced, so I assume you have written a module before (see writing a reusable Terraform module) and know plan and apply. I used Terraform 1.17.1, AWS provider 6.73.0, TFLint 0.66.0 and the AWS ruleset 0.50.0.
The module under test
It's a backup bucket module. You give it a name and an environment, it makes an S3 bucket with versioning, blocks public access, and expires old versions after some days. Prod buckets must never have force_destroy and must keep old versions at least 30 days. Those two rules are exactly the kind of thing someone breaks by accident, so they're what I want tests for.
The variables have validation blocks. These run during plan, before anything touches AWS.
variable "name" {
description = "Bucket name prefix, e.g. shorty-backups"
type = string
validation {
condition = can(regex("^[a-z0-9][a-z0-9-]{1,40}[a-z0-9]$", var.name))
error_message = "name must be 3-42 characters of lowercase letters, digits and hyphens."
}
}
variable "environment" {
description = "dev, staging or prod"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
variable "noncurrent_days" {
description = "Days to keep old object versions"
type = number
default = 30
}
The 30 day rule depends on two variables, so it goes in a precondition on the lifecycle resource.
resource "aws_s3_bucket" "this" {
bucket = local.bucket_name
force_destroy = var.environment != "prod"
tags = {
Environment = var.environment
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket_lifecycle_configuration" "this" {
bucket = aws_s3_bucket.this.id
rule {
id = "expire-old-versions"
status = "Enabled"
filter {}
noncurrent_version_expiration {
noncurrent_days = var.noncurrent_days
}
}
lifecycle {
precondition {
condition = var.environment != "prod" || var.noncurrent_days >= 30
error_message = "prod buckets must keep old versions for at least 30 days."
}
}
depends_on = [aws_s3_bucket_versioning.this]
}
There's also a postcondition, which works the same but runs after the resource is planned or applied and can look at self. I used a precondition on the arn output instead, just to show that outputs can have them too.
The check block
A check block is different. It doesn't stop anything. It runs at the end of plan and apply and prints a warning if the assertion fails. I use it for things that can drift outside Terraform. Here it reads the bucket back with a data source scoped to the check and compares its region to the provider's region.
check "bucket_in_provider_region" {
data "aws_s3_bucket" "this" {
bucket = aws_s3_bucket.this.bucket
}
assert {
condition = data.aws_s3_bucket.this.bucket_region == data.aws_region.current.region
error_message = "bucket ${aws_s3_bucket.this.bucket} is in ${data.aws_s3_bucket.this.bucket_region}, expected ${data.aws_region.current.region}."
}
}
Hold that thought, this check is what broke my first test run itself.
Writing the tests
Tests live in tests/*.tftest.hcl. Each run block is a plan or an apply against the module, with asserts after it. The mock_provider block is the important bit. It replaces the real AWS provider with a fake one that makes up values for every computed attribute, so no credentials and no API calls.
mock_provider "aws" {
mock_data "aws_region" {
defaults = {
region = "ap-south-1"
}
}
mock_resource "aws_s3_bucket" {
defaults = {
arn = "arn:aws:s3:::mock-bucket"
}
}
mock_data "aws_s3_bucket" {
defaults = {
bucket_region = "ap-south-1"
}
}
}
variables {
name = "shorty-backups"
environment = "dev"
}
run "names_bucket_after_environment" {
assert {
condition = aws_s3_bucket.this.bucket == "shorty-backups-dev"
error_message = "bucket name should be <name>-<environment>"
}
assert {
condition = aws_s3_bucket.this.force_destroy
error_message = "dev buckets should be easy to delete"
}
}
run "prod_is_never_force_destroyed" {
variables {
environment = "prod"
}
assert {
condition = aws_s3_bucket.this.force_destroy == false
error_message = "prod bucket must not have force_destroy"
}
}
Tests for the failure cases use expect_failures. The run passes only if exactly that thing fails.
run "rejects_uppercase_name" {
command = plan
variables {
name = "Shorty"
}
expect_failures = [var.name]
}
run "prod_needs_30_days_of_versions" {
command = plan
variables {
environment = "prod"
noncurrent_days = 7
}
expect_failures = [aws_s3_bucket_lifecycle_configuration.this]
}
Three things that tripped me
My first version looked a bit different, and terraform test failed three times before it went green. Each failure taught me something about how the test runner works, so here they are.
First, I had command = plan on the two happy path runs. They failed with this.
Error: Check block assertion known after apply
on main.tf line 63, in check "bucket_in_provider_region":
│ data.aws_region.current.region is "ap-south-1"
│ data.aws_s3_bucket.this.bucket_region is a string
In a normal terraform plan that's only a warning. Inside terraform test a check that can't be evaluated is an error. The data source depends on a bucket that doesn't exist yet, so at plan time its value is unknown, and adding a mock default for it didn't help since the read is deferred anyway. With a mocked provider, apply costs nothing, so I dropped command = plan from those runs (apply is the default) and that was that.
Second, the arn precondition failed.
Error: Module output value precondition failed
│ aws_s3_bucket.this.arn is "jpockygh"
Mock provider fills computed strings with random letters. jpockygh is not an ARN. That's why the mock_resource "aws_s3_bucket" block with a fake ARN is there. Any computed value your code checks needs a sensible default.
Third, a run with override_resource for one specific ARN kept getting mock-bucket back. Runs in one file share state by default, and the bucket already existed from the first run, so nothing got re-created and the override never applied. Basically, giving the run its own state_key fixed it.
run "apply_with_mocks" {
# runs share state by default; a new key gives this run an empty state
state_key = "fresh"
override_resource {
target = aws_s3_bucket.this
values = {
arn = "arn:aws:s3:::shorty-backups-dev"
}
}
assert {
condition = output.arn == "arn:aws:s3:::shorty-backups-dev"
error_message = "arn output should come from the bucket"
}
}
And the check block gets its own test. override_data makes the bucket look like it's in the wrong region, and expect_failures says the check should catch it. I deleted the expect_failures line once just to be sure the test really bites, and it failed with "bucket shorty-backups-dev is in us-east-1, expected ap-south-1". Good.
run "check_warns_on_wrong_region" {
override_data {
target = data.aws_s3_bucket.this
values = {
bucket_region = "us-east-1"
}
}
expect_failures = [check.bucket_in_provider_region]
}
Now the whole thing.
terraform init -backend=false
terraform test
tests/unit.tftest.hcl... in progress
run "names_bucket_after_environment"... pass
run "prod_is_never_force_destroyed"... pass
run "rejects_uppercase_name"... pass
run "prod_needs_30_days_of_versions"... pass
run "apply_with_mocks"... pass
run "check_warns_on_wrong_region"... pass
tests/unit.tftest.hcl... tearing down
tests/unit.tftest.hcl... pass
Success! 6 passed, 0 failed.
The whole file took about seven seconds on my Mac. You can also write tests without a mock, against a real account, and Terraform destroys what it made at the end. I keep those for a separate job with its own sandbox account, if at all.
tflint
terraform validate checks syntax and types. It doesn't know AWS. I put an aws_instance with instance_type = "t3.smal" in the module and validate said "Success! The configuration is valid." tflint with the AWS ruleset knows the real list of instance types. My config:
config {
call_module_type = "local"
}
plugin "terraform" {
enabled = true
preset = "recommended"
}
plugin "aws" {
enabled = true
version = "0.50.0"
source = "github.com/terraform-linters/tflint-ruleset-aws"
}
rule "terraform_documented_outputs" {
enabled = true
}
tflint --init
tflint
On the typo it said this, plus a warning about an unused variable I had added in the same file.
Error: "t3.smal" is an invalid value as instance_type (aws_instance_invalid_type)
And on the real module it found two outputs with no description. Fair enough, I added them. tflint exits non zero when it finds issues (I got exit 2 with only notices), so it fails CI without any extra flags.
Running it on every pull request
Here is the workflow. It only runs when Terraform files change.
name: terraform-test
on:
pull_request:
paths:
- "**.tf"
- "**.tftest.hcl"
- ".tflint.hcl"
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: hashicorp/setup-terraform@v4
with:
terraform_version: 1.17.1
- uses: terraform-linters/setup-tflint@v6
with:
tflint_version: v0.66.0
- name: fmt
run: terraform fmt -check -recursive
- name: init
run: terraform init -backend=false -input=false
- name: validate
run: terraform validate
- name: tflint
run: |
tflint --init
tflint --format compact
env:
GITHUB_TOKEN: ${{ github.token }}
- name: test
run: terraform test
No AWS credentials anywhere in that job, which is the nice part about mocks. The GITHUB_TOKEN is only there so tflint --init doesn't hit the GitHub API rate limit when it downloads the plugin. If you're new to workflow files, GitHub Actions from zero covers the basics, and a CI workflow for Go is the same idea for Go code.
I ran the fmt, validate, tflint and test steps on my Mac. I have not run this exact workflow on GitHub till now, so pin the versions you actually want.
There we have it. Start with one test per rule you'd be upset to see broken, the prod rules here, and add more when something slips through.