Terratest Guide

Terratest is a Go library that provides patterns and helper functions for testing infrastructure code. This guide covers how to effectively use Terratest for testing Terraform configurations as of 2025.

Getting Started

Installation

  1. First, ensure you have Go installed:

go version  # Should be 1.21 or higher
  1. Create a new test directory and initialize a Go module:

mkdir test
cd test
go mod init terraform-tests
  1. Install Terratest:

go get -u github.com/gruntwork-io/terratest@latest

Basic Test Structure

Directory Layout

infrastructure/
β”œβ”€β”€ modules/
β”‚   └── vpc/
β”‚       β”œβ”€β”€ main.tf
β”‚       β”œβ”€β”€ variables.tf
β”‚       └── outputs.tf
└── test/
    β”œβ”€β”€ go.mod
    β”œβ”€β”€ go.sum
    └── vpc_test.go

Simple Test Example

Advanced Testing Patterns

1. Retry Logic

2. HTTP Testing

3. SSH Testing

Testing Cloud-Specific Resources

AWS Resources

Azure Resources

Test Fixtures

1. Example Test Fixture

2. Using Test Fixtures

Test Parallelization

1. Parallel Test Execution

2. Resource Naming for Parallel Tests

Testing Best Practices

1. Environment Cleanup

2. Test Timeouts

3. Test Logging

CI/CD Integration

Troubleshooting

Common Issues and Solutions

  1. State Lock Issues

  1. Provider Authentication

  1. Resource Dependencies

Last updated