Intro

With the exciting new announcement for Terraform Tests I couldn’t help but take them for a test drive. For our use case we will build on a prior post Terraform Azure: Reusable SQL Database Configurations. In the last post we created a module to deploy SQL Servers. Today we will add a new default prefix to SQL Server name and then build a test to check the name of the server.

Update SQL Server Module

We have decided we want all of our SQL Servers to have a standard prefix in their name. For Data Artisans we want to use the prefix dart-. To update the module with this functionality we can use string interpolation.

Develop Test

First thing we want to do is create a new tests folder to store our tests in. Inside of that folder create a new file named sql_server.tftest.hcl. The .tftest.hcl file extension is what Terraform uses to recognize a test file.

Once that’s done we can write out test.

  1. Create a variable for all of the inputs needed to successfully call the module. For the SQL Server module we need the 4 variables listed below.
  2. Initialize the provider needed to establish the resources we want to test.
  3. The last thing we need is called a run block. These are used in tests to control the order you want different code executed. You can have one or many run blocks in a given test.
  4. Specify the module we want to call in our test.
  5. Using assertions we can write out the specific condition we want to test for once the module has been successfully executed. In our use case we want to test that the SQL Server created has the name dart-tf-test.

Run Test

When we run our test Terraform will create the defined resources, check our assertions, and then tear down the resources. To do this we use test command.
A successful run will show the tests passed like below.

To simulate a failure I changed the expected name in our assertion. An unsuccessful run will show the tests failed, output the error we specified in the assertion, and it also gives us the unexpected value.

Closing Thoghts

I like the new testing framework in Terraform 1.6. It gives us a great set of tools to setup standard tests. Could we have accomplished this specific use case by running a plan and inspecting the values? Sure we could. What I really like here is that it actually creates the resources and tests what was created. A plan can show success, but the apply can still fail. Having the rubber hit the road here is where I see the value.

You can go follow the tutorial Hashicorp published for another use case example.