Writing Terraform Tests

Terraform tests allow you to verify your module configurations without impacting your existing state or resources. Testing in Terraform is separate from the regular plan or apply workflows. Instead, it temporarily builds infrastructure and tests assertions against in-memory states for short-lived resources. This process enables you to safely validate changes without affecting your existing infrastructure.

In this tutorial, you’ll learn how to write Terraform tests and use helper modules to validate your configuration. The example module in this tutorial creates an S3 bucket and uploads files to host a static website. You’ll also learn how to write your own tests, using a helper module to generate a random bucket name as an input.

Once you’ve completed the initial tests, you’ll create your own helper module to ensure that the static website is running and responding properly. You’ll also explore the process of publishing the module to the HCP Terraform private module registry.

Prerequisites

You’ll also need:

  • Terraform  installed 
  • An AWS account with credentials configured for Terraform use
  • A GitHub account
  • An HCP Terraform account

Step 1: Create the Example Repository

  • Go to the template repository  for this tutorial and click the Use this template button. Then, select Create a new repository.
  • Name your repository terraform-aws-s3-website-tests and leave the default settings.
  • Clone your new repository by replacing USER with your GitHub username: $ git clone https://github.com/USER/terraform-aws-s3-website-tests
  • Clone your new repository by replacing USER with your GitHub username:

$ git clone https://github.com/USER/terraform-aws-s3-website-tests

  • Change into your repository directory:

$ cd terraform-aws-s3-website-tests

Step 2: Review the Example Configuration

Your configuration files should have:

  • main.tf : it defines an S3 bucket and resources for uploading files to it.
  • www/ : it contains source files for a Terraform-based Tetris game (Terramino).
  • Test files : they end with the .tftest.hcl extension and are located in the tests/ directory. The setup folder contains helper modules to generate test-specific resources.

By default, when you run terraform test, Terraform looks for .tftest.hcl files in the root and tests/ directories. You can use the -test-directory flag to specify a different location.

Terraform tests consist of:

  • Test files: These contain the test logic.
  • Optional helper modules: These create test-specific resources or data sources outside the main configuration.

In this tutorial, a helper module in the tests/setup/ directory generates a random bucket name using the random provider. You can review the helper module in tests/setup/main.tf.

 

Step 3: Review Test File Overview

Next, review the test configuration in tests/website.tftest.hcl. This file defines the test assertions and includes multiple run blocks.

  • The first run block, setup_tests, runs the helper module to create the random bucket name.
  • The second run block, create_bucket, applies the main configuration to create the S3 bucket. It includes assertions to verify the bucket name and the hashes of index.html and error.html.

Step 4: Run the tests

Initialize the Terraform configuration to install the required providers. Any time you add a new provider or module to your configuration or tests, you must run the terraform init command.

 

This installs the required providers and prepares your environment. Once initialized, you can run the tests:

 

Terraform will apply the setup helper module, create the S3 bucket, and run assertions to ensure everything is working. If all assertions pass, you’ll see a success message.

Step 5: Create a New Helper Module

Now that you’ve run the initial tests, it’s time to create your own helper module to test whether the static website is running.

  • Create a new directory for the helper module: $ mkdir tests/final
  • Inside this directory, create main.tf with the following content:

 

This module uses the http provider to perform an HTTP GET request to the website endpoint.

Step 6: Add the New Test

Add the following test at the end of tests/website.tftest.hcl to check if the website is running:

 

This test uses the new helper module to verify that the website responds with an HTTP 200 status code, indicating it’s up and running.

Step 7: Run the Tests Again

  • After adding the new test, reinitialize the environment: $ terraform init
  • Then, run the tests again: $ terraform test

Terraform will execute the new test and confirm whether the website is running.

As your module configuration evolves, you can use tests to confirm your assumptions and ensure predictability for your module consumers.

Push these changes to your GitHub repository. First, stage your changes.

 

Then, commit the changes to your local main branch.

Finally, push the changes to the remote main branch.

Step 8: Publish the module

  • To publish your module, navigate to your organization’s HCP Terraform registry, click Publish, then select Module.
  • Select your version control provider, then select your terraform-aws-s3-website-tests repository.

    On the Add Module screen, choose Branch for the module publish type and provide the following values.

 

  • Check Enable testing for Module, then click Publish module
  • When you publish a module using the branch-based workflow, HCP Terraform displays a Branch-Based badge next to the module name, as well as the branch and commit SHA that your module version references.

Step 9: Configure the module tests

Since the tests for this module deploy resources to AWS, you must provide credentials for the tests to use. To configure environment variables for the test, click Configure Tests.

Under Module variables, click + Add variable and add the following environment variables.

  • Navigate back to the module: Click on Module overview to return to the module.

Step 10: Update the module

Tests are essential to ensure that changes to your modules do not introduce breaking issues. In this example, you’ll confirm that updating the module’s provider version is safe.

Open the terraform.tf file and update the AWS provider version to 5.16.0.

Reinitialize your configuration with the -upgrade flag to update your Terraform lock file with the new provider version.

Commit the changes to your local main branch.

Push the changes to the remote main branch.

On your module’s overview page, HCP Terraform reports your module’s running tests a few moments after you push your changes.

Click View all tests. Here, HCP Terraform shows the history of all test runs, starting with the latest run.

  • View test details: Click on the latest test run to review the details of the tests for your changes.

  • Check individual test steps: Open the File: tests/website.tftest.hcl dropdown to view the status of each test step. If any tests fail, HCP Terraform will provide detailed output for the failed test, helping you troubleshoot the issue effectively.

By following these steps, you’ve successfully added new tests, verified your module’s functionality, and published it for use.

Leave a Reply

Your email address will not be published. Required fields are marked *