Terraform Test Files and Referencing Variables from *.auto.tfvars

Hi everyone,

I’m currently using Terraform’s testing framework ( *.tftest.hcl files). I’m leveraging *.auto.tfvars files to provide input variable values to my tests.

For example, in my my.tftest.hcl file, I configure the Google provider like this:

provider “google” {
project = var.gcp_project
}

The value for var.gcp_project is sourced from a corresponding *.auto.tfvars file. This setup functions correctly, and the tests execute as expected.

However, I’m encountering the following warning:

Warning: Variable referenced without definition

│ on tests/my.tftest.hcl line 3, in provider “google”:
│ 3: project = var.gcp_project

│ Variable “gcp_project” was referenced without providing a definition.
│ Referencing undefined variables within Terraform Test files is deprecated,
│ please add a variable block into the relevant test file to provide a
│ definition for the variable. This will become required in future versions
│ of Terraform.

The warning suggests defining the variable within the test file. I attempted to create a variables.tf file in the same directory as my.tftest.hcl, defining gcp_project there. However, this resulted in a “Variable declared but not used” warning, indicating that *.tftest.hcl files don’t seem to recognize variable definitions in variables.tf.

So, my question is: what is the correct way to declare the var.gcp_project variable within the context of a *.tftest.hcl file & auto.tfvars to eliminate this warning ?

Any guidance would be greatly appreciated!

I ended up using the following workaround. I created a module (a folder within tests folder) which I named “importtfvars”.

In this module, I define variables.tf and outputs.tf.

In outputs.tf, it looks as follows:

output “region” {
value = var.region
}

The value of region is well retrieved from my auto.tfvars file.

In my hcl.tftest, I have to reference these values as importtfvars.region, and the warning of undeclared variable disappeared.

Regards.

The proper solution is given in the answer here: Terraform Test outputs variable referenced without definition deprecation warning · Issue #37754 · hashicorp/terraform · GitHub

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.