Back to Terraform

Integration Tests, Terratest and Real Service Readiness

November 5, 2026 Wasil Zafar 20 min read

Exercise the cloud behavior that mocks and plan assertions cannot prove

Table of Contents

  1. Test the Smallest Useful Slice of Real Infrastructure
  2. Choose Native Apply Tests or a Test Harness
  3. Inject Dependencies and Isolate Concurrent Test Runs
  4. Wait for Readiness Without Retrying Every Failure
  5. Always Have a Teardown and Reconciliation Route
  6. Prove the Endpoint Works and Then Prove It Is Gone

Test the Smallest Useful Slice of Real Infrastructure

A building inspector can read a fire-door specification, watch one door close, or run a full evacuation. Each answers a different question at a different cost. Infrastructure testing has the same three gears, and running the evacuation after every hinge change is expensive.

A module integration test applies one module, or a small fixture around it, into a disposable account and asserts outputs, attributes and wiring: a rule that names another group, a health-check path of /healthz. Its scope is one contract. A service end-to-end test applies the composition that serves traffic and makes a real request through the entry point, proving the listener reaches a healthy target. An application test exercises handlers and business rules without Terraform; it belongs to the application repository.

The smallest useful slice is the smallest graph containing the failure you fear. A security-group reference needs two groups and one rule. A listener that never reaches a healthy target needs the listener, target group, one instance and health check. A wrong page needs an application test; Terraform cannot answer that. The web-service lab's nine resources justify a full service test before a release, because balancer, health check and bootstrap interact in ways plan cannot prove, but not on every pull request.

Figure 1 maps that choice.

Test the Smallest Useful Slice of Real Infrastructure
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Behavior needs proof"] --> B{"Plan assertion?"}
    B -->|"yes"| C["Native plan test"]
    B -->|"no"| D{"Terraform value or wiring?"}
    D -->|"yes"| E["Module integration"]
    D -->|"no"| F{"HTTP or SDK call?"}
    F -->|"no"| G["Re-examine"]
    F -->|"yes"| H["Service end-to-end"]
    H --> I{"App logic alone?"}
    I -->|"yes"| J["Application test"]
    I -->|"no"| K["Service test: nightly"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class A,B,D,F,I primary;
    class C,E,H secondary;
    class J ok;
    class G danger;
    class K warn;

Figure 2 draws the boundaries: the module contract ends at its outputs, the service boundary runs from DNS name to response, and the application boundary sits inside the process. Account, region and quota sit outside all three.

Module, service and application test boundaries Account and region: identity, quota, bill Module contract variables and outputs groups and rules Service boundary ALB DNS name in health check and listener Application handler and template unit tests, no Terraform Outside every boundary quota · shared default VPC Not proved by a green apply boot finished · target healthy · page served Evidence: outputs · status and body · target health · test result

Choose Native Apply Tests or a Test Harness

Native tests are HCL, not Go. Terraform 1.17.1 reads .tftest.hcl files from tests/, applies each run block, and evaluates assertions against configuration values and earlier outputs.

# tests/service.tftest.hcl
run "setup" {
  module {
    source = "./tests/setup"
  }
}

run "service" {
  command = apply

  variables {
    name_prefix = "p24-test"
    vpc_id      = run.setup.vpc_id
    subnet_ids  = run.setup.subnet_ids
  }

  assert {
    condition     = startswith(output.alb_url, "http://")
    error_message = "The balancer must expose an HTTP URL."
  }
}
terraform init
terraform fmt -check
terraform validate
terraform test -junit-xml=report.xml

Plan mode is the cheap unit test. Point the run at command = plan; expect_failures then covers validation and check blocks, and a state key separates runs that would otherwise share state.

Cleanup and reporting are automatic. Terraform destroys each file's resources in reverse order, and -junit-xml gives CI a report.

Terratest is a Go library that drives the real terraform or tofu binary. A test applies a module, reads its outputs, and makes HTTP or SDK calls from the same process.

The assertion is ordinary Go, so it can do what HCL cannot. Parse JSON, query target health, retry with a deadline or audit the account.

The cost is a second toolchain. Terratest v2.0.0, released 23 September 2026, requires Go 1.26+ and moved imports under /v2; this lab uses its Terraform, HTTP and random modules.

Table 1 compares them; manual verification is useful for exploration, not as a gate.

DimensionNative terraform testTerratest v2Manual verification
LanguageHCL and Terraform CLIGo 1.26+, Terraform or OpenTofuBrowser and console
AssertionsExpressions, outputs, attributesAny HTTP, SDK or shell checkWhat a person notices
ReadinessProvider waits onlyBounded retries and deadlinesAd hoc
TeardownAutomatic per test filedefer terraform.DestroyManual delete
StateIn memory per test fileTemp directory or isolated backendWhatever was open
CI costLow: one binaryMedium: Go build plus cloud timeHigh per repetition
Best useModule contracts and plan checksService end-to-end and inventory auditExploration and incidents

The practical split is a ladder. Native plan tests run on every pull request, native apply tests when a module contract changes, and Terratest nightly and before releases touching the balancer, health check, bootstrap or network. Choose Go only when the team can maintain it.

Figure 3 shows the mechanics and the exits that matter: a false assertion and an unfinished destroy.

Choose Native Apply Tests or a Test Harness
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Test starts"] --> B["terraform init"]
    B --> C{"plan or apply?"}
    C -->|"plan"| D["Evaluate expressions"]
    C -->|"apply"| E["Create fixture and module"]
    D --> F{"Assertion true?"}
    E --> G["Assert outputs and attributes"]
    F -->|"no"| X1["Fail: show condition"]
    F -->|"yes"| H["Destroy at end of file"]
    G --> I{"External behavior unproven?"}
    I -->|"no"| H
    I -->|"yes"| J["Terratest: InitAndApply"]
    J --> K["HTTP or SDK check with deadline"]
    K --> L{"Pass?"}
    L -->|"no"| X2["Fail: last response and target state"]
    L -->|"yes"| M["defer Destroy"]
    H --> N{"Destroy clean?"}
    M --> N
    N -->|"no"| X3["Report leaks by tag"]
    N -->|"yes"| O["Pass, empty inventory"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class A,C,F,I,L,N primary;
    class B,D,E,G,J,K secondary;
    class H,M,O ok;
    class X1,X2,X3 danger;

Inject Dependencies and Isolate Concurrent Test Runs

The web-service lab hard-codes p07-web for the balancer, target group and security groups. Two CI jobs collide on the second apply, and the failure looks like a Terraform bug rather than a test-design bug.

Duplicate names are a test-design bug

The second apply fails with DuplicateLoadBalancerName or InvalidGroup.Duplicate. The lab is telling you its names are global, not that the provider is broken.

Names must be inputs. Add a name_prefix variable, validate its length, and derive every constrained name from it.

The provider caps target-group and ALB names at 32 characters, with no leading or trailing hyphen. Use a short prefix plus six random characters: Go's random.UniqueID() returns six, while Terraform's random_id adds state you must clean up.

Dependencies should be injected, not discovered. A test that calls data "aws_vpc" "default" inherits whatever the account contains, including a deleted VPC.

A setup fixture owns the network. It returns the network IDs, and the module under test receives them as variables. A native setup run loads a local module and the next run references its outputs; Terraform destroys the fixture in reverse order. In Terratest, apply the fixture first or create it with the AWS SDK.

State must be independent too. Native tests keep in-memory state per test file, which is the isolation you want but also means a killed process cannot resume it. Terratest should run in a copied directory or a dedicated working directory with local state, never against a production backend. A shared remote backend turns two parallel tests into a race over one lock.

Concurrency is a quota calculation before it is a code change. One run creates two instances, two vCPUs, one ALB and two public IPv4 addresses; four parallel runs need eight vCPUs and four balancers. An account with the common five-vCPU On-Demand quota fails the third run with VcpuLimitExceeded.

Do the quota math first

Check Service Quotas, leave headroom, then cap the harness. Native tests use parallel runs with distinct state_key values and a run-parallelism flag; Go tests call t.Parallel() only when the math supports it. Isolation is a matrix: separate state, unique names, injected dependencies, a quota budget and a dedicated account.

Wait for Readiness Without Retrying Every Failure

Apply complete! Resources: 9 added is an API receipt, not a readiness signal. It does not mean cloud-init finished, httpd bound port 80, the target passed two checks or the balancer can serve. The lab checks every 15 seconds with a healthy threshold of 2, so a new target takes about 30 seconds to enter; a cold install can push that past two minutes. A 503 in that window is normal.

Readiness failures fall into three buckets, and only two deserve a retry. Eventual consistency is convergence on an accepted state: target initial, ALB DNS not propagated, IAM still spreading. Retry within the documented window. Transient errors are throttles, 5xx, resets and temporary DNS failures; retry with backoff and jitter, capped by attempts and time. Persistent defects are a wrong health path, missing rule, no route to the package mirror, port mismatch, image without httpd, IAM denial or quota. Retrying those turns two minutes into ten with a larger bill.

Classify by evidence, not by elapsed time.

EvidenceReadingRetry?
HTTP 503No healthy target behind the listenerYes, within budget
HTTP 502Target answered badlyOnly if the target is converging
TimeoutPacket never arrivedCheck route and group first
HTTP 404Wrong pathNo: fix the health check
Throttling, RequestLimitExceeded, ServiceUnavailableTransient control-plane pressureYes, with backoff and jitter
AccessDenied, ValidationError, AlreadyExistsPersistent permission or configuration defectNo
Target initial or drainingConvergingYes
Target unhealthy with Target.ResponseCodeMismatchDefectNo: fix path, port or bootstrap

Log attempt, status, target state and body prefix. Fail with the last observation rather than a generic timeout.

Bound the loop explicitly. Allow perhaps 30 attempts over five minutes for health and five over thirty seconds for a control-plane call. Use a context so a hung request cannot outlive the budget. Do not use sleep 300; it hides fast failures and still fails at 301 seconds.

Native assertions run once, which suits plan and contract checks and is why readiness usually moves to Terratest. Go can poll with httphelper.HttpGetWithRetry or wrap a status-and-body function in retry.DoWithRetry. The retry count is not a deadline; set both. Figure 4 shows the path: recover within budget or fail with evidence.

Classify a readiness failure before retrying it Observation 503, initial, throttle Classify evidence status, code, target state Bound the budget attempts plus deadline Converging initial, DNS, IAM Transient 429, 5xx, reset Persistent 404, 403, denied Recovered 200 and two hosts Recovered after retry record delay and attempts Budget exhausted last response and state A 404 or missing route is still wrong after thirty attempts.

Always Have a Teardown and Reconciliation Route

Every test needs two exits: the happy path that destroys and the failure path that still destroys.

A hard kill leaves no state to destroy

Terraform's native framework destroys what it created when a file finishes, in reverse order, and reports what it could not remove. But state lives in memory: after SIGKILL, a lost runner or a badly timed cancellation, there is no state file and no terraform destroy. The tag is the only handle.

Terratest makes the happy path explicit. Build the options struct, defer the destroy call before the apply, and let that deferred call run on return, failed assertion or panic.

A deferred call still does not survive a hard kill. Set the Go timeout above apply plus destroy; -timeout 45m gives a slow balancer time to disappear, while the default ten minutes often panics first.

CI interruption is normal: a cancelled job, preempted runner, expired OIDC session or workflow timeout. The provider can also fail a delete: a group referenced by an ENI, a non-empty bucket, a target group attached to a listener, deletion protection, or DependencyViolation. Read the diagnostic and retry the dependency-ordered delete once; do not hide it with -refresh=false or a rename.

The reconciliation route is a tag-based sweeper in a dedicated test account. Tag every resource with lab, run_id, owner and expires_at; a scheduled job deletes expired tags and reports what it cannot delete. The test also runs a post-destroy inventory and fails if the tag still returns resources.

Figure 5 follows apply through deferred destroy to a clean exit or a quarantined leak.

Teardown and reconciliation route Apply succeeds nine tagged resources Assertions run pass or fail Deferred destroy runs on return or panic Process killed state lost, tag remains Delete fails DependencyViolation Retry once after dependency clears Clean exit inventory returns nothing Tagged leak quarantine, alert, keep run id Scheduled sweeper deletes expired tags

Prove the Endpoint Works and Then Prove It Is Gone

A credible report has six pieces: apply summary, outputs or resource IDs, target health, a real request with status and body, destroy summary, and post-destroy inventory. The first three prove Terraform built the stack; the fourth proves it serves; the last two prove no bill remains.

Prove the endpoint through the public entry point, not an instance address. The URL output gives the DNS name; the checks below turn it into evidence.

ProofHowPass condition
EndpointRequest /healthz, then / twice with Connection: close200 with ok, and two different hostnames
Target healthaws elbv2 describe-target-health for the target groupTwo healthy targets
CleanupQuery the lab tag, then balancers, instances, volumes, addresses, groups and target groupsNo ARNs, no resources

Closing the connection prevents keep-alive from pinning both requests to one target, so two hostnames prove both serve.

A 200 is liveness, not readiness

A 200 from a static file proves the server is alive, not ready. If the application needs a database or migration before serving, give it a separate readiness endpoint and keep non-critical dependencies out of the gate.

Prove cleanup by tag, not memory. The tag query returns ARNs; follow it with service queries for every resource type the lab can create. Run them in the region you used.

The lab below combines a Go service test with the inventory check. The widget is the code; the card is the run order, expected result and failure map.

package test

import (
	"os"
	"testing"
	"time"

	"github.com/gruntwork-io/terratest/modules/core/v2/random"
	"github.com/gruntwork-io/terratest/modules/httphelper/v2"
	"github.com/gruntwork-io/terratest/modules/terraform/v2"
)

func TestP24Service(t *testing.T) {
	t.Parallel()

	opts := &terraform.Options{
		TerraformDir: "../examples/web-service",
		Vars: map[string]interface{}{
			"name_prefix":  "p24-" + random.UniqueID(),
			"lab":          "p24-integration",
			"allowed_cidr": os.Getenv("TF_VAR_allowed_cidr"),
		},
	}

	defer terraform.Destroy(t, opts)
	terraform.InitAndApply(t, opts)

	url := terraform.Output(t, opts, "alb_url")
	httphelper.HttpGetWithRetry(t, url+"/healthz", "", 200, 30, 5*time.Second)
}
# Replace the placeholder address with your own /32
export TF_VAR_allowed_account_id="$(aws sts get-caller-identity --query Account --output text)"
export TF_VAR_region="us-east-1"
export TF_VAR_allowed_cidr="198.51.100.10/32"

cd test && go mod tidy
go test -v -timeout 45m -run TestP24Service ./...

The empty body argument means the helper checks the status code, not the exact body.

Lab

Run one real service test

Status: design-only. No AWS account or credential was used, and these commands were not executed. Run them in a disposable sandbox, record sanitized evidence, and redact account identifiers.

Prerequisites. Terraform 1.17.1, AWS provider 6.72.0, Go 1.26+, Terratest v2.0.0, AWS CLI v2, and an SSO profile for a dedicated test account with EC2, ELBv2 and security-group permissions. The account needs a default VPC with two subnets in two zones; set a budget alarm first.

Minimal setup.

  1. Copy the web-service lab into examples/web-service.
  2. Add the prefix and lab inputs, and replace the fixed names, capped at 32 characters.
  3. Put the Go test in test/, and add default tags for lab, run id and expiry.
  4. Export the three TF_VAR_ values from the bash tab and confirm the account.

Run order.

  1. Sign in, clear inherited keys, and confirm the caller with aws sts get-caller-identity.
  2. Run init, format check and validate; tidy the Go module in test/ and commit the lock file.
  3. Run the test, and poll target health in another terminal: expect initial or unhealthy, then two healthy targets.
  4. Capture the health response and two page responses; record both hostnames.
  5. Run the tag inventory and service queries. Expect no p24-integration resources; if the test failed, confirm the deferred destroy still ran.
  6. Failure drill: point the health path at /missing, rerun, and confirm a 503 or unhealthy target inside the deadline instead of a hang. Interruption drill: cancel during apply, run the inventory, delete tagged leftovers and record their lifetime.
  7. Check Cost Explorer by the lab tag, delete reports after redacting identifiers, remove local state and plans, and run aws sso logout.

Expected result.

  • Targets: two healthy.
  • Health endpoint: 200 with ok.
  • Page requests: two different hostnames.
  • Destroy: service removed and tag inventory empty.

Failure map.

SignalMeaningFirst move
VcpuLimitExceededQuota or parallel runs are too highReduce parallelism or request quota
DuplicateLoadBalancerName / InvalidGroup.DuplicateName collision or earlier leakSweep the tag, then rerun
503 with targets initialConvergenceWait inside the budget
unhealthyPath, port, group or bootstrap wrongFix the target, do not retry
TimeoutWeb group or subnet routeCheck the route table
DependencyViolationENI, listener or bucket still references the resourceRetry once, then find the reference

Cost dimensions. Two t3.micro instances, two volumes, two public IPv4 addresses, one ALB with hourly and capacity charges, and transfer. A short run costs cents to a few tenths of a dollar, dominated by the balancer; a leaked balancer bills until deleted.

Cleanup. Release an unassociated Elastic IP, delete an available volume, and remove any test log group, bucket, key pair or AMI. Inventory the region used, delete plans and reports, keep state out of Git, and confirm with the API.

References (verified 5 November 2026):

  • https://developer.hashicorp.com/terraform/language/tests
  • https://developer.hashicorp.com/terraform/cli/commands/test
  • https://terratest.gruntwork.io/docs/

Next in the Series

In Production Changes: Upgrades, Availability and Release Evidence, we'll explore Promote versioned changes using availability criteria, capacity checks and reviewable evidence.