Search code examples
goterraformterratest

Difference between variables passed in terraform.Options for Terratest and terraform.tfvars?


I get terraform.Options is for testing purposes but what is the purpose of it when my Terratest can get the variable values from the tfvars file? How can I utilize it to it's max ability?

Also, most of my variables in tfvars are nested. How would I map that out in terraform.Options?

#variable in tfvars
resource_group = {
  resource_group1 = { 
    rg_name = "Terratest1"
    #resource group location
    location = "us"
    #tags
    tags = {
      foo = "foo"
      bar = "bar"
    }
  }
  resource_group2= {
    rg_name  = "Terratest2"
    location = "us"
    tags = {
      foo = "foo"
      bar = "bar"
    }
  }
}
#how would I map in terraform.Options?
    terraformOptions := &terraform.Options{
        // The path to where our Terraform code is located
        TerraformDir: "../../examples/azure/terraform-azure-resourcegroup-example",
        Vars: map[string]interface{}{
            "postfix": uniquePostfix,
        },
    }

Solution

  • I get terraform.Options is for testing purposes but what is the purpose of it when my Terratest can get the variable values from the tfvars file?

    One of the important aspects of testing is to vary the inputs, and validate the behavior and outputs based on those inputs. You can use terraform.Options to provide a variety of inputs to a module, and then determine that the behavior and outputs of the module are as expected. If this is a root module config, then that value is significantly diminished. If this is a reusable and often declared module, then there is substantial value.

    How would I map that out in terraform.Options?

    With nested type constructors most easily:

    terraformOptions := &terraform.Options{
        // path to terraform module
        TerraformDir: "../../examples/azure/terraform-azure-resourcegroup-example",
        // map of input variables to module
        Vars: map[string]interface{}{
            "resource_group1":  map[string]interface{}{
                "rg_name":  "Terratest1",
                "location": "us",
                "tags ":    map[string]string{
                    "foo": "foo",
                    "bar": "bar",
                },
            },
            "resource_group2":  map[string]interface{}{
                "rg_name":  "Terratest2",
                "location": "us",
                "tags ":    map[string]string{
                    "foo": "foo",
                    "bar": "bar",
                },
            },
        },
    }