Skip to main content

Terraform Testing with Terratest

Write infrastructure tests using Terratest in Go to validate Terraform modules with integration tests, retries, and cleanup.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Write Terratest tests for a Terraform module that provisions VPC, subnets, security groups, ECS cluster, and ALB on AWS. The module is used in 3 environments and needs confidence before production applies. Implement: 1) Test file structure: test/network_test.go with TestMain for setup, individual test functions for default configuration, high-availability mode, minimal dev mode, and shared helpers in a test/helpers package. 2) Basic deployment test: run terraform init/plan/apply using terratest terraform.Options with smaller instance types, single AZ, reduced retention periods to minimize cost to create isolated test resources, validate outputs match expectations, then destroy. Use t.Parallel() where possible. 3) Validation tests for each critical resource: VPC has correct CIDR, subnets are in expected AZs, ALB returns 200 on health check, security group allows only specified ports — use AWS/GCP/Azure SDK calls (e.g., aws.GetSubnet, http_helper.HttpGetWithRetry) to verify resources were created correctly and are functional, not just that Terraform says they exist. 4) Retry logic using terratest retry.DoWithRetry for ALB health check (takes time to register targets), DNS propagation, ECS service stability with 10 retries and 30 seconds sleep between attempts. 5) Test cleanup with defer terraform.Destroy even if tests fail — implement CloudWatch log groups, EBS snapshots, ENIs left by Lambda in VPC for resources that Terraform destroy might miss. 6) Test randomization: use random.UniqueId() for resource naming to allow parallel test runs without conflicts, and rotate between us-east-1, us-west-2, eu-west-1 to distribute API limits for test region selection. 7) Integration with GitHub Actions: test stage configuration, timeout settings (30 minutes per test), and cost management (auto-destroy after 2 hours).

What this prompt does

This prompt writes Terratest tests in Go for a Terraform module that provisions [module_resources] on [cloud_provider], used across [environment_count] environments. It scaffolds the test file structure (test/[module_name]_test.go with TestMain for setup, per-scenario functions for [test_scenarios], and a shared helpers package), then a basic deployment test that runs init/plan/apply with [tfvars_overrides], validates outputs against expectations, and destroys, using t.Parallel() where possible.

The key value is real validation: for each critical resource it makes cloud SDK calls ([resource_validations]) to confirm resources are actually functional, not just that Terraform claims they exist. It adds retry logic via retry.DoWithRetry for [flaky_operations] with [max_retries] attempts and [retry_sleep] between them, defer terraform.Destroy plus [cleanup_extras] for resources Terraform might miss, random.UniqueId() naming for parallel runs, a [region_strategy] for test regions, and CI integration with [ci_system], a [test_timeout] per test, and auto-destroy after [max_age]. A module nobody tested is a module that breaks in production, so these checks call the cloud SDKs directly rather than trusting the plan.

When to use it

  • You have a Terraform module you don't trust until it's tested against real cloud APIs
  • You want validation that resources work, not just that the plan applied
  • You need retries for flaky checks like ALB target registration or DNS propagation
  • You want reliable cleanup even when tests fail partway
  • You're running tests in parallel and need conflict-free resource naming
  • You want CI integration with timeouts and automatic cost cleanup
  • You're gaining confidence in a module before it touches production environments

Example output

The AI returns Go test files with terraform.Options and [tfvars_overrides], SDK-based validation functions for [resource_validations], retry.DoWithRetry wrappers for [flaky_operations], deferred destroy plus [cleanup_extras] logic, random.UniqueId() naming, and a CI config for [ci_system] with a [test_timeout] and auto-destroy after [max_age]. Expect Go code blocks grouped by the seven numbered concerns, so the validation and cleanup patterns are easy to reuse across modules.

Pro tips

  • Validate functionality, not existence — use SDK calls in [resource_validations] (for example, an HTTP 200 from the ALB) rather than trusting Terraform output alone
  • Wrap genuinely flaky steps from [flaky_operations] in retry.DoWithRetry with sensible [max_retries] and [retry_sleep], since target registration and DNS take time
  • Always defer terraform.Destroy so a failed assertion doesn't leave resources running and billing
  • Add [cleanup_extras] for orphans Terraform misses, like leftover ENIs or CloudWatch log groups
  • Use random.UniqueId() in naming so parallel tests don't collide on resource names
  • Shrink resources with [tfvars_overrides] (single AZ, smaller instances) so test runs stay cheap without changing the code path
  • Rotate test regions with [region_strategy] so parallel runs spread API calls and don't trip per-region rate limits
  • Cap each test with [test_timeout] and auto-destroy after [max_age] to control cost when CI hangs

Frequently Asked Questions

Does Terratest just check that Terraform applied, or that resources actually work?
It does real validation. For each critical resource in `[resource_validations]`, the tests make cloud SDK calls, like confirming an ALB returns 200 on its health check, so they verify the infrastructure is functional rather than trusting that Terraform reported success.
How does it handle flaky operations like DNS propagation?
It wraps unstable checks in `[flaky_operations]` with Terratest's `retry.DoWithRetry`, retrying up to `[max_retries]` times with `[retry_sleep]` between attempts. This covers things like ALB target registration and DNS propagation that aren't ready the instant Terraform finishes.
Will it clean up resources if a test fails?
Yes. It uses `defer terraform.Destroy` so cleanup runs even when assertions fail, and adds `[cleanup_extras]` for resources Terraform's destroy might miss, such as CloudWatch log groups or ENIs left by Lambda in a VPC. CI also auto-destroys after `[max_age]` as a safety net.
Can these tests run in parallel without conflicting?
They can. The prompt uses `random.UniqueId()` for resource naming so concurrent runs don't collide, applies `t.Parallel()` where safe, and rotates regions via `[region_strategy]` to spread cloud API rate limits across runs.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Terraform & Infrastructure as Code Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support