terratest
Terratest is a Go library that makes it easier to write automated tests for your infrastructure code.
Top Related Projects
Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
A Pluggable Terraform Linter
Generate documentation from Terraform modules in various output formats
Prevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.
Quick Overview
Terratest is a Go library that provides a collection of helper functions and patterns for testing infrastructure code, particularly for Terraform, Packer, and Kubernetes. It allows developers to write automated tests for their infrastructure code, ensuring reliability and consistency in deployments.
Pros
- Enables writing automated tests for infrastructure code, improving reliability and reducing errors
- Supports multiple infrastructure tools like Terraform, Packer, and Kubernetes
- Provides a rich set of helper functions for common testing scenarios
- Integrates well with existing Go testing frameworks
Cons
- Requires knowledge of Go programming language to write tests
- Can be complex to set up and use for beginners in infrastructure testing
- May have slower test execution times due to the nature of infrastructure provisioning
- Limited to testing infrastructure code, not suitable for general-purpose testing
Code Examples
- Testing a Terraform module:
func TestTerraformAwsExample(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../examples/terraform-aws-example",
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
publicIp := terraform.Output(t, terraformOptions, "public_ip")
http_helper.HttpGetWithRetry(t, "http://"+publicIp, nil, 200, "Hello, World!", 30, 5*time.Second)
}
- Testing a Kubernetes deployment:
func TestKubernetesHelloWorldExample(t *testing.T) {
options := k8s.NewKubectlOptions("", "", "default")
defer k8s.KubectlDelete(t, options, "examples/kubernetes-hello-world-example.yml")
k8s.KubectlApply(t, options, "examples/kubernetes-hello-world-example.yml")
k8s.WaitUntilServiceAvailable(t, options, "hello-world-service", 10, 1*time.Second)
service := k8s.GetService(t, options, "hello-world-service")
endpoint := fmt.Sprintf("%s:%d", service.Spec.ClusterIP, service.Spec.Ports[0].Port)
http_helper.HttpGetWithRetry(t, fmt.Sprintf("http://%s", endpoint), nil, 200, "Hello, World!", 30, 5*time.Second)
}
- Testing SSH connectivity:
func TestSshConnection(t *testing.T) {
publicHost := "example.com"
publicKey := "~/.ssh/id_rsa.pub"
sshAgent := ssh.SshAgentWithKeyPair(t, publicKey)
defer sshAgent.Stop()
host := ssh.Host{
Hostname: publicHost,
SshUserName: "ubuntu",
SshAgent: sshAgent,
}
ssh.CheckSshConnection(t, host, 30, 5*time.Second)
}
Getting Started
To use Terratest in your Go project:
- Install Go (version 1.13 or later)
- Initialize a Go module:
go mod init your-module-name
- Install Terratest:
go get github.com/gruntwork-io/terratest@latest
- Create a test file (e.g.,
main_test.go
) and import Terratest:
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
)
func TestExample(t *testing.T) {
// Your test code here
}
- Run your tests:
go test -v ./...
Competitor Comparisons
Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
Pros of Terraform
- Primary infrastructure-as-code tool for defining and provisioning infrastructure
- Extensive provider ecosystem for various cloud platforms and services
- Declarative language for describing desired infrastructure state
Cons of Terraform
- Not designed specifically for testing infrastructure code
- Lacks built-in testing frameworks or assertion capabilities
- Requires additional tools or custom scripts for comprehensive testing
Code Comparison
Terraform (main.tf):
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
Terratest (example_test.go):
func TestTerraformAwsExample(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../examples/terraform-aws-example",
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
}
Key Differences
- Terraform focuses on infrastructure provisioning, while Terratest is specifically designed for testing infrastructure code
- Terratest provides a Go-based testing framework with built-in assertions and helper functions for infrastructure testing
- Terraform uses HCL (HashiCorp Configuration Language), whereas Terratest uses Go for writing tests
- Terratest can be used to test Terraform configurations, as well as other infrastructure-as-code tools
While Terraform is essential for defining and managing infrastructure, Terratest complements it by providing a robust testing framework for infrastructure code, ensuring reliability and correctness of deployments.
A Pluggable Terraform Linter
Pros of tflint
- Focused specifically on linting Terraform code, providing more specialized and in-depth checks
- Faster execution time for static code analysis
- Easier integration into CI/CD pipelines for continuous linting
Cons of tflint
- Limited to static code analysis, lacking the ability to perform actual infrastructure tests
- Does not support testing of deployed resources or infrastructure behavior
- Less comprehensive in terms of overall infrastructure validation
Code Comparison
tflint example:
resource "aws_instance" "example" {
ami = "ami-12345678"
instance_type = "t2.micro"
}
Terratest example:
func TestAwsInstance(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../examples/terraform-aws-example",
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
instanceID := terraform.Output(t, terraformOptions, "instance_id")
aws.AssertInstanceRunning(t, instanceID, "us-west-2")
}
While tflint focuses on static analysis of Terraform code, Terratest allows for actual deployment and testing of infrastructure. tflint is more suitable for quick syntax and best practice checks, while Terratest provides comprehensive infrastructure testing capabilities.
Generate documentation from Terraform modules in various output formats
Pros of terraform-docs
- Focused specifically on generating documentation for Terraform modules
- Lightweight and easy to integrate into CI/CD pipelines
- Supports multiple output formats (Markdown, JSON, YAML, etc.)
Cons of terraform-docs
- Limited to documentation generation, lacks testing capabilities
- Does not provide infrastructure validation or deployment checks
Code comparison
terraform-docs:
# Generate Markdown documentation
terraform-docs markdown . > README.md
# Generate JSON documentation
terraform-docs json . > output.json
Terratest:
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestTerraformModule(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../",
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
output := terraform.Output(t, terraformOptions, "example_output")
assert.Equal(t, "expected_value", output)
}
Summary
terraform-docs is a specialized tool for generating documentation from Terraform modules, while Terratest is a comprehensive testing framework for infrastructure code. terraform-docs excels in simplicity and documentation generation, whereas Terratest offers robust testing capabilities for Terraform configurations.
Prevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.
Pros of Checkov
- Focuses on static code analysis and security scanning
- Supports multiple IaC languages (Terraform, CloudFormation, Kubernetes, etc.)
- Provides out-of-the-box policies and customizable rules
Cons of Checkov
- Limited to static analysis, doesn't perform actual infrastructure testing
- May produce false positives or miss runtime issues
- Requires separate integration for dynamic testing
Code Comparison
Checkov (policy-based scanning):
check = Check()
@check.check_resource("aws_s3_bucket")
def check_s3_bucket_encryption(resource):
if "server_side_encryption_configuration" not in resource:
return CheckResult.FAILED
return CheckResult.PASSED
Terratest (infrastructure testing):
func TestS3BucketEncryption(t *testing.T) {
bucketName := "my-test-bucket"
aws.CreateS3Bucket(t, awsRegion, bucketName)
defer aws.DeleteS3Bucket(t, awsRegion, bucketName)
aws.AssertS3BucketEncrypted(t, awsRegion, bucketName)
}
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Terratest
Terratest is a Go library that makes it easier to write automated tests for your infrastructure code. It provides a variety of helper functions and patterns for common infrastructure testing tasks, including:
- Testing Terraform code
- Testing Packer templates
- Testing Docker images
- Executing commands on servers over SSH
- Working with AWS APIs
- Working with Azure APIs
- Working with GCP APIs
- Working with Kubernetes APIs
- Testing Helm Charts
- Making HTTP requests
- Running shell commands
- And much more
Please see the following for more info:
- Terratest Website
- Getting started with Terratest
- Terratest Documentation
- Contributing to Terratest
- Commercial Support
License
This code is released under the Apache 2.0 License. Please see LICENSE and NOTICE for more details.
Copyright © 2020 Gruntwork, Inc.
Top Related Projects
Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
A Pluggable Terraform Linter
Generate documentation from Terraform modules in various output formats
Prevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot