How to test terraform's HCL code

2 min read | by Jordi Prats

To be able to learn about new terraform functions we can use terraform output to learn how a variable is modified. But this can take a while if we have a lot of resources to compute.

Instead, if we know the values we want to use beforehand it might be easier and quicker to use terraform console

There are several ways we can use terraform console. Interactively on any empty directory to test functions:

$ terraform console
> cidrsubnet("10.12.0.0/16", 8, 0)
"10.12.0.0/24"

But we can also pipe the code to execute like this:

$ echo 'coalesce(null, "", "test")' | terraform console
"test"

To use more complex data types, such as maps, we can create a file with a variable that has the data as it's default like follows:

$ mkdir /tmp/tftest
$ cd /tmp/tftest
$ echo 'variable "map" { default = {"a"="A", "b"="B"} }' > var.tf
$ terraform console
> var.map
{
  "a" = "A"
  "b" = "B"
}

This way we will be able to use it as an input variable within the terraform console session:

$ terraform console
> var.map["a"]
"A"

Posted on 22/04/2022

Categories