terraform test - creating and asserting unit test in terraform

 

In this example, we will be creating a simple storage account and then testing it with terraform test.

Let start off with the following scripts 

variable "account_name" { type = string }
variable "resource_group_name" { type = string }
variable "location" { type = string }

variable "environment" {
type = string
description = "The environment for the deployment."

validation {
# The condition must return true for the variable to be accepted.
condition = contains(["dev", "staging", "prod"], var.environment)
# This is the message printed to the screen if the condition is false.
error_message = "Validation Error: The environment must be 'dev', 'staging', or 'prod'."
}
}

resource "azurerm_storage_account" "this" {
name = var.account_name
resource_group_name = var.resource_group_name
location = var.location
account_tier = "Standard"
account_replication_type = "LRS"
}

resource "azurerm_storage_container" "this" {
name = "content"
storage_account_id = azurerm_storage_account.this.id
container_access_type = "private"
}

output "storage_account_id" {
value = azurerm_storage_account.this.id
}

And then we create another file call storage.tftest.hcl. This file must end with .tftest.hcl or tftest.json. In the command here, we are trying to run our test parallelly and then set the command to use plan (setting it to unit test) 

The mock_provider is crucial for our test to run. If you do not have this, terraform will look for full implementation - this means you need to have provider {} specified in here

The script "run" is use to mark a test case. Then we have assert and condition in our block for our testing


# 1. Tell Terraform to fake the Azure (or AWS) provider
mock_provider "azurerm" {}

test {
parallel = true
}

# 3. Run the test in memory
run "verify_naming_convention" {

command = plan

variables {
account_name = "myappstorage"
resource_group_name = "rg-myapp"
location = "eastus"
environment = "dev"
}

assert {
condition = azurerm_storage_account.this.name == "myappstorage"
error_message = "The storage account name did not map correctly."
}
}

run "verify_location" {
command = plan

variables {
account_name = "myappstorage"
resource_group_name = "rg-myapp"
location = "eastus"
environment = "sandbox"
}

assert {
condition = azurerm_storage_account.this.location == "eastus"
error_message = "The storage account location did not map correctly."
}

expect_failures = [
var.environment
]
}



And in the last expect.failure block here, this means we specifically passing in environment = "sandbox" which intentially fail the test but we are aware of it hence expecting a failure to occur. 







Comments

Popular posts from this blog

vllm : Failed to infer device type

android studio kotlin source is null error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20