IaC Testing with Terratest: Automate Infrastructure Validation
Infrastructure as Code (IaC) has revolutionized how infrastructure is provisioned and managed. However, automating the setup and configuration of infrastructure requires thorough testing to ensure reliability. This is where IaC testing comes in. In this blog post, we will explore IaC testing with a particular focus on using Terratest, a powerful tool for automating the validation of your infrastructure code.

What is Infrastructure as Code (IaC)?
Infrastructure as Code (IaC) refers to the practice of managing and provisioning infrastructure using code instead of manual processes. By writing code, you can automate tasks like setting up virtual machines, configuring storage, and deploying software. IaC tools like Terraform, Packer, and Ansible allow for version control and modularization, ensuring that infrastructure can be replicated and managed efficiently across different environments.
One of the main advantages of IaC is disaster recovery. If your infrastructure becomes corrupted or lost, you can quickly recreate it in another region or environment, minimizing downtime.
Why Test Your Infrastructure Code?
As the infrastructure becomes increasingly automated, testing IaC becomes crucial to ensure it works as expected. Automated testing can identify issues early, preventing costly mistakes before deployment. There are several stages to IaC testing:
- Sanity or Static Analysis
- Unit Testing
- Integration Testing
Sanity or Static Analysis
The first stage in IaC testing is static analysis. This phase ensures that the code follows correct syntax and adheres to industry best practices. Tools like foodcritic for Chef, tflint for Terraform, and hadolint for Docker images are examples of static analysis tools that help detect syntax and style issues early in the process.
Unit Testing
Unit testing evaluates the logic of your infrastructure code without provisioning any resources. For example, you might check whether containers are running as non-root users or if security settings are correct. Tools like Conftest for Terraform can be used for such tests, ensuring that the infrastructure code adheres to security and operational policies.
package main
deny[msg] {
input.kind == "Deployment"
not input.spec.template.spec.securityContext.runAsNonRoot
msg := "Containers must not run as root"
}
Integration Testing
Integration testing goes one step further by deploying actual infrastructure and verifying its functionality. For instance, after deploying a virtual machine with Nginx running on port 80, you can test whether the port is accessible. This phase helps confirm that the infrastructure not only deploys correctly but also functions as intended.
describe port(80) do
it { should be_listening }
end
Now, let’s dive deeper into Terratest and how it helps automate IaC testing.
What is Terratest and How Does it Help?
Terratest is a Go-based library designed to automate the testing of infrastructure code, particularly IaC written with Terraform. Terratest allows you to test infrastructure across various cloud platforms like AWS, Azure, and Google Cloud, as well as container platforms like Kubernetes.
With Terratest, you can perform both sanity checks and functional tests for your infrastructure. Additionally, it supports compliance testing, making it easier to verify that your infrastructure meets security and regulatory standards. Some of its capabilities include testing Docker images, Helm charts, and Packer templates.
Terratest can also integrate with ZippyOPS‘s consulting and managed services in DevOps, DevSecOps, Cloud, Automated Ops, and more, making it a great choice for enterprise environments. Learn more about ZippyOPS Services and Solutions for DevOps and infrastructure automation.
How to Get Started with Terratest
To begin using Terratest, you need two essential tools: Terraform and Go. These tools form the foundation of Terratest, enabling you to write, test, and deploy your infrastructure code seamlessly.
Installing Terraform
- Visit the Terraform downloads page.
- Choose your platform and install it using either a package manager or a manual binary.
After installation, confirm Terraform is set up by running:
terraform version
Installing Go
Install Go by using your system’s package manager or follow the official Go installation guide.
Terratest in Action
Once the required tools are set up, you can start writing tests for your IaC. Terratest tests are written in Go, and the test files should end with _test.go. Here’s an example of a simple test that verifies the SSH key on an EC2 instance provisioned by Terraform.
package terratest
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/gruntwork-io/terratest/modules/terraform"
)
func TestEc2SshKey(t *testing.T) {
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../terraform",
})
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
ec2SshKey := terraform.Output(t, terraformOptions, "instance_ssh_key")
assert.Equal(t, "terratest", ec2SshKey)
}
This test initializes and applies the Terraform configuration, then verifies that the EC2 instance’s SSH key matches the expected value.
Advanced IaC Testing with Terratest
Once you are comfortable with basic tests, you can proceed to more complex scenarios, such as deploying an API Gateway with Lambda and testing the connectivity. Here’s an example of testing the availability of an API Gateway after deployment:
func TestApiGateway(t *testing.T) {
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../",
})
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
stageUrl := terraform.Output(t, terraformOptions, "deployment_invoke_url")
time.Sleep(30 * time.Second)
statusCode := DoGetRequest(t, stageUrl)
assert.Equal(t, 200, statusCode)
}
func DoGetRequest(t terra_test.TestingT, api string) int {
resp, err := http.Get(api)
if err != nil {
log.Fatalln(err)
}
return resp.StatusCode
}
This test checks whether the deployed API Gateway responds with a 200 OK status code.
Compliance Testing with Terratest
Terratest also supports compliance testing. For instance, you can verify that encryption is enabled on an S3 bucket or check API Gateway settings, such as authentication configurations.
For more details on compliance testing, explore ZippyOPS Solutions to integrate best practices in security and DevSecOps.
Conclusion: Automate and Ensure IaC Testing Quality
As more infrastructure is automated through IaC, testing becomes critical to ensure smooth deployments. Tools like Terratest provide automated tests to validate IaC, ensuring that your infrastructure is both secure and functional. Whether you are testing basic configurations or performing advanced compliance checks, Terratest helps you catch issues before they affect your production environment.
For more information on automating infrastructure, check out our services or products.
If you are looking for personalized support in DevOps or infrastructure automation, feel free to contact us at sales@zippyops.com.



