Writing automated tests for your infrastructure code can be a breeze: Meet Terratest
It’s hardly a secret that maintaining a large codebase of infrastructure code is not the easiest or most pleasant task. That said, this Go library might come in handy since it offers a variety of helper functions and patterns for common infrastructure testing tasks.
Infrastructure as code (IaC) tools are a blessing and a curse; they surely have their benefits but maintaining a large codebase of infrastructure code can be a challenge. Not to mention that this is basically the textbook definition of the butterfly effect: changes (as insignificant as they might seem) to infrastructure code might lead to severe bugs.
If you want to face your fears and stop being afraid of making changes to your infrastructure code, you’ll need Terratest, a Go library which promises to make it easier to write automated tests for your infrastructure code.
It provides helper functions and patterns for common infrastructure testing tasks such as:
- Testing Terraform code
- Testing Packer templates
- Testing Docker images
- Executing commands on servers over SSH
- Working with AWS APIs
- Making HTTP requests
- Running shell commands
- and the list goes on.
As Yevgeniy Brikman, co-founder of Gruntwork, the company behind Terratest, wrote in a recent blog post, this library is “worth the effort because these tests can run after every commit and verify that the code works as expected, thereby giving you the confidence to make the code changes you need.” The good news is that Terratest is now open source [under the Apache 2.0 license]. You can find it on GitHub.
Get started with Terratest
First things first: install Go.
To add Terratest to your projects, you should use a Go dependency manager such as dep:
dep ensure -add github.com/gruntwork-io/terratest
Alternatively, you can use
go get github.com/gruntwork-io/terratest
Basic usage pattern for writing automated tests with Terratest
- Write tests using Go’s built-in package testing: you create a file ending in
_test.goand run tests with the
go testcommand. E.g.,
go test my_test.go.
- Use Terratest to execute your real IaC tools (e.g., Terraform, Packer, etc.) to deploy real infrastructure (e.g., servers) in a real environment (e.g., AWS).
- Use the tools built into Terratest to validate that the infrastructure works correctly in that environment by making HTTP requests, API calls, SSH connections, etc.
- Undeploy everything at the end of the test.
You might want to check the testing beta practices guide before you take Terratest for a spin.
During initial development, the major version will be 0 (e.g.,
0.x.y), which means that the code does not yet have a stable API. Once Terratest hits
1.0.0, the team will try to maintain a backwards compatible API and use the MAJOR, MINOR, and PATCH versions on each release to indicate any incompatibilities.