DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 14 of 17
Your progress · 0%
On this page
  1. terraform test
  2. Integration tests
  3. Terratest
↖ Course roadmap
Lesson 14 · Testing

Testing Terraform code

Test modules with terraform test: plan-only and apply runs, assertions and expect_failures. Then see where integration tests with Terratest fit, and what to test at each level.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
Lab status

Verified lab: terraform test failing, then passing with expect_failures. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: Terratest and mock providers: explained, not run.
Cloud lab: Terratest applies real infrastructure in a test account.

Once a module is used by several teams, "I'll check the plan" isn't enough: a small change can break someone else's environment. Terraform has a built-in test framework, and for bigger modules there are integration tests that build real infrastructure. This lesson starts with a test that fails, because it found a real gap in the module from lesson 10.

Most tests belong at the bottom. Real-infrastructure tests are for modules many people depend on.© Diagram: DevOps Academy

Most tests belong at the bottom. Real-infrastructure tests are for modules many people depend on.© Diagram: DevOps Academy

terraform test

Tests live in files ending in .tftest.hcl, usually in a tests/ folder next to the module. Run terraform test from the module folder. Each file has:

  • variables: input values for every run in the file.
  • run blocks: each one plans or applies the module, then checks assertions.

The lab's test for the site module:

# tests/site.tftest.hcl
variables {
  name  = "shop"
  pages = ["index", "cart"]
}

run "creates_one_file_per_page" {
  command = plan

  assert {
    condition     = length(local_file.page) == 2
    error_message = "Expected one file per page."
  }
}

run "file_names_use_the_site_name" {
  command = apply

  assert {
    condition     = alltrue([for f in output.files : startswith(f, "./out/shop/")])
    error_message = "Every file should live under out/shop/."
  }
}

run "rejects_an_empty_page_list" {
  command = plan

  variables {
    pages = []
  }

  assert {
    condition     = length(local_file.page) > 0
    error_message = "A site needs at least one page."
  }
}

What each run does:

  1. creates_one_file_per_page only plans (command = plan), so nothing is created. It checks the planned resources: two pages in, two files out.
  2. file_names_use_the_site_name applies for real, then checks the module's output. At the end of the file, terraform test destroys everything the runs created.
  3. rejects_an_empty_page_list overrides pages with an empty list and expects the module to refuse it.

The first run: a real failure

$ terraform test
tests/site.tftest.hcl... in progress
  run "creates_one_file_per_page"... pass
  run "file_names_use_the_site_name"... pass
  run "rejects_an_empty_page_list"... fail

Error: Test assertion failed

  on tests/site.tftest.hcl line 32, in run "rejects_an_empty_page_list":
  32:     condition     = length(local_file.page) > 0
    ├────────────────


A site needs at least one page.
tests/site.tftest.hcl... tearing down
tests/site.tftest.hcl... fail

Failure! 2 passed, 1 failed.
terraform test
  • terraforminfrastructure as code

The module happily planned a site with zero pages. Nothing in it said that was wrong. That's exactly what tests are for.

The fix, and a better test

First, make the module reject the bad input with a validation rule (lesson 6):

# variables.tf
variable "pages" {
  description = "Page names to create."
  type        = list(string)
  default     = ["index"]

  validation {
    condition     = length(var.pages) > 0
    error_message = "A site needs at least one page."
  }
}

Then the test should check that validation fails. That's what expect_failures is for: the run passes only if the listed object fails its check.

run "rejects_an_empty_page_list" {
  command = plan

  variables {
    pages = []
  }

  expect_failures = [var.pages]
}
$ terraform test
tests/site.tftest.hcl... in progress
  run "creates_one_file_per_page"... pass
  run "file_names_use_the_site_name"... pass
  run "rejects_an_empty_page_list"... pass
tests/site.tftest.hcl... tearing down
tests/site.tftest.hcl... pass

Success! 3 passed, 0 failed.
terraform test
  • terraforminfrastructure as code

If someone later deletes the validation block, this test fails again. That's a test that protects something.

More test features

  • mock_provider "aws" {} (Terraform 1.7+) fakes a provider, so apply-mode tests run with no cloud account and no cost; computed values get made-up placeholders.
  • module { source = "./tests/setup" } inside a run uses a helper module, for example to create a VPC the module under test needs.
  • Runs share state in order, so a later run can read run.<name>.<output> from an earlier one.
  • Put terraform test in the same CI job as validate. Plan-only tests need no credentials.

Integration tests

Plan-mode tests prove the code would do the right thing. Integration tests prove the real result works: apply in a sandbox account, then check from the outside that, say, the load balancer answers on port 80 and the bucket really refuses public reads, then destroy.

They're slow (minutes) and cost money, so use them for modules many teams depend on, run them on a schedule or before a release rather than on every commit, and always in a separate test account with a budget alarm.

Terratest

Terratest is an open-source Go library from Gruntwork for these integration tests. A test reads like this (not run for this course; it needs Go and a cloud account):

// test/site_test.go
package test

import (
	"testing"

	"github.com/gruntwork-io/terratest/modules/terraform"
	"github.com/stretchr/testify/assert"
)

func TestSite(t *testing.T) {
	opts := &terraform.Options{
		TerraformDir: "../examples/basic",
		Vars:         map[string]interface{}{"name": "shop"},
	}
	defer terraform.Destroy(t, opts) // always clean up, even if the test fails

	terraform.InitAndApply(t, opts)

	files := terraform.OutputList(t, opts, "files")
	assert.Equal(t, 1, len(files))
}

InitAndApply runs real Terraform, Output... reads outputs, and Terratest has helpers to make HTTP requests, SSH into servers and query AWS. With terraform test now built in, many teams start there and add Terratest only where they need Go's flexibility.

⌘
Mini mission

Write a test that catches a real bug

For the site module from lesson 10, write tests/site.tftest.hcl with a plan-mode run counting files, an apply-mode run checking output paths, and a run proving an empty page list is rejected. Run it, see the last run fail, add the validation block, and run again until all three pass.

Input: modules/site from lesson 10Output: tests/site.tftest.hcl
Reveal one safe solution
$ cd modules/site && mkdir -p tests
$ terraform init && terraform test
$ # add the validation block and expect_failures, then:
$ terraform test
cd modules/site && mkdir -p tests
  • cdchange directory
  • &&run the next command only if this one worked
  • mkdirmake a directory
  • -pcreate missing parents, no error if it exists
terraform init && terraform test
  • terraforminfrastructure as code
  • initdownload providers, set up the folder

The lab went from Failure! 2 passed, 1 failed. to Success! 3 passed, 0 failed. If the first run passes all three, your module already validates pages: remove the rule and watch the test catch it.

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

What does command = plan in a run block mean?

Go deeper

Official reading for this lesson

  • DocsTerraform testsHashiCorp ↗
  • Docsterraform test commandHashiCorp ↗
  • DocsMocks in Terraform testsHashiCorp ↗
  • ToolTerratestGruntwork ↗
  • GuideWrite Terraform tests (tutorial)HashiCorp ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousTerraform in CI/CDNext lesson →Scaling Terraform: split state, Terragrunt, Infracost