Search code examples
goterraformdevopsterratest

Doing terraform script test with terratest but facing errors exit status 1


I am using terratest to test terraform, I want to make sure that the terraform makes the resource group,container registry and AKS, When I do go test -v -timeout 60m all the resources are made and destroyed but at the end I dont know why it throws

TestTerraformAzureResources 2024-02-09T18:45:51+05:00 logger.go:66: 
Destroy complete! Resources: 4 destroyed.
TestTerraformAzureResources 2024-02-09T18:45:51+05:00 logger.go:66: 
--- FAIL: TestTerraformAzureResources (691.95s)
FAIL
exit status 1
FAIL    my-terratest-project    691.996s

Below is my terraform_test.go code

package test

import (
"testing"

"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)

func TestTerraformAzureResources(t *testing.T) {
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
    TerraformDir: "../terraform scripts",
})

defer terraform.Destroy(t, terraformOptions)

terraform.InitAndApply(t, terraformOptions)

// Retrieve the outputs of the Terraform configuration
resourceGroupName := terraform.Output(t, terraformOptions, "resource_group_name")
acrName := terraform.Output(t, terraformOptions, "acr_name")
aksName := terraform.Output(t, terraformOptions, "aks_name")

// Define the expected values
expectedResourceGroupName := "microservice-deployment-demo-tf- 
scripttest"
expectedACRName := "microserviceimagestfscripttest"
expectedAKSName := "example-aks1-tf-scripttest"

// Compare the outputs with the expected values
assert.Equal(t, expectedResourceGroupName, resourceGroupName, "Resource 
group name does not match")
assert.Equal(t, expectedACRName, acrName, "Azure Container Registry name 
does not match")
assert.Equal(t, expectedAKSName, aksName, "Azure Kubernetes Cluster name 
does not match")
}

Edited : Below are the errors I revived Error: Received unexpected error: FatalError{Underlying: error while running command: exit status 1; Error: Output "resource_group_name" not found The output variable requested could not be found in the state file. If you recently added this to your configuration, be sure to run terraform apply


Solution

  • I solved the issue by adjusting the outputs.tf file, Configuring it in such a way that it store the values like aks named etc in variables. Below is the outputs.tf file

    output "resource_group_name" {
      value = azurerm_resource_group.demoresourcegroup.name
    }
    
    output "acr_name" {
      value = azurerm_container_registry.acr.name
     }
    
    output "aks_name" {
      value = azurerm_kubernetes_cluster.aks.name
    }