Terraform test 1.6 > Any way to use functions within test to create new variables?

I’m using more and more the new terraform test framework from 1.6.x but I’m facing a frustrating limitation and was not able to find something relevant in the documentation.

I would like to declare some variables with “dynamic” content using function, for example upper(var.env_name) or a more comple for loop construct.
Locals blocks are not allowed so no change there…
When trying this kind of syntax in a variables block, I’m getting:

$ terraform test
tests\unit.tftest.hcl... in progress
  run "setup_resourcegroup"... fail
╷
│ Error: Function calls not allowed
│
│   on tests\unit.tftest.hcl line 32, in run "setup_resourcegroup":
│   32:     env_code = upper("d") # "D"
│
│ Functions may not be called here.

Any way to get dynamic data inside a test file?

Hi @sebastien.latre, thanks for the feedback.

There’s good and bad news. The good news is that this is supported in Terraform v1.7.0 which was released last week. The bad news is there is a bug preventing file-level variable blocks from accessing functions at the moment. But functions referenced from within run-level variable blocks should work in v1.7.0. File-level variables will get access to functions in v1.7.1 once the fix is released.

If you are stuck on v1.6.0 for any reason, you can get an approximation of this by creating a dedicated setup module with your dynamic values returned as outputs. You can then reference these outputs from later run blocks, giving you access to your dynamic variables.

Hopefully that answers your questions!
Thanks!

Hello @liamcervante, again a valuable answer to one of my posts :slight_smile:

I will go for 1.7.x as soon as possible to benefit your improvements, probably when 1.7.1 is coming. Any release date forecast?

Another point, do you have some issue related to this bug you’re talking about, I would like to reference it in our issue tracker.
Thanks !

Hopefully we’ll see v1.7.1 this week, we usually do releases on Wednesdays so we’d be targeting the 24th January. If not this week, then definitely next week.

And yes, the issue is terraform test: referencing variables at testing file level results in a crash · Issue #34529 · hashicorp/terraform · GitHub. It’s closed as the fix has been merged already.

Thanks!

1 Like