Terratest + LocalStack: Testing AWS Infrastructure Without Cloud Costs
Real Terratest runs against AWS are slow (5-15 minutes per test), expensive ($0.01-10 per run depending on resources), and require AWS credentials in CI. For fast feedback during development, LocalStack is the answer: a fully local AWS mock that runs in Docker and supports S3, Lambda, SQS, DynamoDB, IAM, and 200+ other services.
This guide covers how to wire Terratest to LocalStack, what you can and can't test locally, and how to structure a test suite that uses LocalStack for fast unit tests and real AWS for pre-deployment integration tests.
What LocalStack Supports
LocalStack Community (free) covers:
- S3, SQS, SNS, Lambda, DynamoDB, IAM, CloudWatch Logs
- API Gateway, Kinesis, Secrets Manager, SSM Parameter Store
- CloudFormation (basic support)
LocalStack Pro adds:
- RDS, ElasticSearch, EKS, MSK, AppSync, and more
- Enhanced CloudFormation support
For most application infrastructure (Lambda + API Gateway + DynamoDB + S3), the free tier is sufficient.
Setup
Start LocalStack
# docker-compose.yml
version: "3.8"
services:
localstack:
image: localstack/localstack:latest
ports:
- "4566:4566"
environment:
- SERVICES=s3,sqs,lambda,dynamodb,iam
- DEBUG=0
volumes:
- /var/run/docker.sock:/var/run/docker.sockdocker compose up -d localstackVerify it's running:
aws --endpoint-url=http://localhost:4566 s3 lsInstall Terratest
go mod init my-infra-tests
go get github.com/gruntwork-io/terratest/modules/terraform
go get github.com/gruntwork-io/terratest/modules/aws
go get github.com/stretchr/testify/assertConfiguring Terraform for LocalStack
Terraform needs to point at LocalStack instead of AWS. Use a provider_override.tf in your test:
# modules/s3-bucket/main.tf (your module)
resource "aws_s3_bucket" "this" {
bucket = var.bucket_name
tags = {
Environment = var.environment
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket_versioning" "this" {
bucket = aws_s3_bucket.this.id
versioning_configuration {
status = "Enabled"
}
}# test/provider_override.tf (injected during tests only)
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
s3 = "http://localhost:4566"
dynamodb = "http://localhost:4566"
lambda = "http://localhost:4566"
sqs = "http://localhost:4566"
iam = "http://localhost:4566"
}
}Writing a Terratest Test Against LocalStack
// test/s3_module_test.go
package test
import (
"testing"
"os"
"path/filepath"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestS3BucketModule_LocalStack(t *testing.T) {
t.Parallel()
bucketName := "test-bucket-" + randomID()
// Copy provider override to module directory
setupLocalStackProvider(t, "../modules/s3-bucket")
defer teardownLocalStackProvider(t, "../modules/s3-bucket")
tfOptions := &terraform.Options{
TerraformDir: "../modules/s3-bucket",
Vars: map[string]interface{}{
"bucket_name": bucketName,
"environment": "test",
},
EnvVars: map[string]string{
"AWS_DEFAULT_REGION": "us-east-1",
},
NoColor: true,
}
defer terraform.Destroy(t, tfOptions)
terraform.InitAndApply(t, tfOptions)
// Verify bucket was created
awsRegion := "us-east-1"
// Use LocalStack endpoint
os.Setenv("AWS_ENDPOINT_URL", "http://localhost:4566")
actualBucketName := terraform.Output(t, tfOptions, "bucket_name")
assert.Equal(t, bucketName, actualBucketName)
// Check versioning is enabled
versioningStatus := aws.GetS3BucketVersioning(t, awsRegion, bucketName)
assert.Equal(t, "Enabled", versioningStatus)
}
func setupLocalStackProvider(t *testing.T, moduleDir string) {
t.Helper()
overrideContent := `
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
s3 = "http://localhost:4566"
}
}
`
err := os.WriteFile(
filepath.Join(moduleDir, "provider_override.tf"),
[]byte(overrideContent),
0644,
)
require.NoError(t, err)
}
func teardownLocalStackProvider(t *testing.T, moduleDir string) {
t.Helper()
os.Remove(filepath.Join(moduleDir, "provider_override.tf"))
}Testing DynamoDB Tables
func TestDynamoDBModule_LocalStack(t *testing.T) {
t.Parallel()
tableName := "test-table-" + randomID()
tfOptions := &terraform.Options{
TerraformDir: "../modules/dynamodb-table",
Vars: map[string]interface{}{
"table_name": tableName,
"billing_mode": "PAY_PER_REQUEST",
},
}
defer terraform.Destroy(t, tfOptions)
terraform.InitAndApply(t, tfOptions)
// Verify table exists and has correct config
awsRegion := "us-east-1"
tableDescription := aws.GetDynamoDBTableDescription(t, awsRegion, tableName)
assert.Equal(t, "ACTIVE", *tableDescription.TableStatus)
assert.Equal(t, tableName, *tableDescription.TableName)
}Testing Lambda Functions
LocalStack supports executing Lambda functions locally:
func TestLambdaModule_LocalStack(t *testing.T) {
t.Parallel()
functionName := "test-function-" + randomID()
tfOptions := &terraform.Options{
TerraformDir: "../modules/lambda-function",
Vars: map[string]interface{}{
"function_name": functionName,
"handler": "index.handler",
"runtime": "nodejs18.x",
},
}
defer terraform.Destroy(t, tfOptions)
terraform.InitAndApply(t, tfOptions)
// Invoke the function
payload := `{"key": "value"}`
response := aws.InvokeFunction(t, "us-east-1", functionName, payload)
assert.Equal(t, int64(200), *response.StatusCode)
assert.NotEmpty(t, string(response.Payload))
}Running Tests in CI Without AWS Credentials
# .github/workflows/terraform-test.yml
name: Terraform Tests
on: [push, pull_request]
jobs:
localstack-tests:
name: Unit Tests (LocalStack)
runs-on: ubuntu-latest
services:
localstack:
image: localstack/localstack:latest
ports:
- 4566:4566
env:
SERVICES: s3,sqs,lambda,dynamodb,iam
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: "1.21" }
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: "1.7.0" }
- name: Run LocalStack tests
run: go test ./test/... -v -run ".*LocalStack.*" -timeout 10m
env:
AWS_DEFAULT_REGION: us-east-1
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
aws-tests:
name: Integration Tests (Real AWS)
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
environment: aws-staging
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: { go-version: "1.21" }
- uses: hashicorp/setup-terraform@v3
- name: Run AWS integration tests
run: go test ./test/... -v -run ".*AWS.*" -timeout 60m
env:
AWS_DEFAULT_REGION: ${{ vars.AWS_REGION }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}What LocalStack Can't Test
LocalStack is excellent for structural tests (does the resource exist? is it configured correctly?) but falls short on:
- IAM authorization — policy evaluation is simulated, not identical to real AWS
- Service limits and throttling — LocalStack doesn't enforce AWS limits
- Complex CloudFormation — stacks with custom resources or complex dependencies
- Cross-region behavior — replication, Route53 routing
- Cost — LocalStack can't tell you what something will cost
For these, you need real AWS. Use LocalStack for fast iteration, real AWS for pre-deployment validation.
Test Organization Strategy
test/
unit/ # LocalStack tests — fast, no AWS credentials
s3_module_test.go
dynamodb_module_test.go
lambda_module_test.go
integration/ # Real AWS tests — slower, requires credentials
full_stack_test.go
cross_region_test.goRun with build tags:
//go:build !integration
// +build !integration
package test
// LocalStack tests (default)//go:build integration
// +build integration
package test
// Real AWS tests (run with: go test -tags integration)Conclusion
Terratest + LocalStack gives you fast, free, credential-free infrastructure tests that run in CI without AWS access. Use LocalStack tests for resource configuration validation and module contract testing. Reserve real AWS tests for pre-deployment integration checks. The combination cuts your infrastructure test feedback loop from 15 minutes to under 2 minutes for most module changes.