Terraform Part-12

UNIT Testing Terraform

We can write test cases for Terraform scripts, like how you write JUnit tests for Java. Here are the main approaches:

1. Using terraform plan & terraform apply with Assertions

We can run terraform plan in a CI/CD pipeline and validate the expected changes using tools like grep, jq, or Terratest.

2. Using terraform validate

  • terraform validate checks syntax and correctness.
  • It ensures that the Terraform configuration is valid but does not test deployments.

terraform validate

3. Using terraform fmt for Code Style

  • Ensures your Terraform code is formatted properly.

terraform fmt -check

4. Using terraform plan with jq for Assertions

  • Extracts and validates the expected changes before applying.

terraform plan -out=tfplan.binary

terraform show -json tfplan.binary | jq ‘.resource_changes[] | select(.type==”aws_instance”)’

5. Using Terratest (Golang)

Terratest is a popular framework for writing Terraform tests in Go.

Example Test:

package test

import (

    “testing”

    “github.com/gruntwork-io/terratest/modules/terraform”

    “github.com/stretchr/testify/assert”

)

func TestTerraformInfra(t *testing.T) {

    terraformOptions := &terraform.Options{

        TerraformDir: “../terraform”,

    }

 

    defer terraform.Destroy(t, terraformOptions)

    terraform.InitAndApply(t, terraformOptions)

    instanced := terraform.Output(t, terraformOptions, “instance_id”)

    assert.NotEmpty(t, instanceId)

}

go test -v

6. Using Checkov (Static Code Analysis)

Checkov helps enforce security best practices.

pip install checkov

checkov -d .

7. Using Kitchen-Terraform (Test Infra with Ruby)

You can use Kitchen-Terraform for integration testing.

gem install kitchen-terraform

kitchen test

Which One Should You Use?

  • Basic Syntax Checks: terraform validate
  • Format Enforcement: terraform fmt
  • Pre-Deployment Verification: terraform plan
  • Unit & Integration Testing: Terratest
  • Security Best Practices: Checkov

Would you like a sample test case for your Terraform script?