This blog explains how to use new terraform test
framework to test infrastructure automation scripts.
Pre-requisites: Install Terraform v1.6.0 or later version, Azure subscription, code editor (Visual studio code use as the code editor in this blog)
What is the use of terraform test?
Terraform has introduced new test framework which
helps to achieve
- Validate terraform configuration updates and get verified new changes does not introduce any breaking changes.
- Terraform test supports running test against test environment which allows to create short lived resources without breaking existing resources.
Demo
Add following terraform configuration files which
create a resource group and a storage account in Azure.
Main.tf – This file has main configuration
provider.tf – information about providers
variable.tf – variables use in main configuration
After adding terraform configuration files, add test file as explained below.
Create folder called tests in the same level as
terraform configuration files as shown in the following image. Add test file
with tftest.hcl extension. (ex: main.tftest.hcl)
test file(tftest.hcl) file consists with
following sections.
- variables - Provide input variables for configurations from the test file.
- run – There are multiple sections such as variables, modules, commands, assertions, etc. in the run block.
- provider - Override required providers in main configuration files using testing files.
main.tftest.hcl
- First set values for resourceprefix, accname and tier variables using the test file.
- There are two run blocks in the test file as TC01_verify_users and TC_02_verify_storage_acc with following sections.
- command - can use as plan or apply. If you put apply as a command, resources will get created in provided azure subscription and get deleted once test is completed. (If providers block provided in test file, it will override required providers in main configuration files and allows to use different subscriptions for testing)
- assert - provide condition to check and error message to throw in case of condition failure.
- Initialize the working directory.
terraform init
- Run test.
terraform test
You would be able to see test run results as below.
Find a sample code in GitHub
No comments:
Post a Comment