Definition
To test expressions in Terraform/Tofu there is an interactive console, which can be called via tofu console
/terraform console
A very convenient thing for checking what the expression will give at the output without resorting to output and test runs
An example for counting the number of nodes from a network of the format <IP>:<MASK>
:
tofu console
> pow(2, 32 - split("/", "172.16.0.0/20")[1]) - 2
4094
>pow(2, 32 - split("/", "10.0.0.0/8")[1]) - 2
16777214
You can pass a variable with -var 'NAME=VALUE'
, a file with variables with -var-file=FILENAME
or, if the file has the extension <name>.auto.tfvars
, they will be automatically included in the console (as with any other Terraform/Tofu commands):
It is important to note that the variables passed must be defined in the corresponding .tf
files
Practice
The easiest way to use it is in a directory with all Terraform/Tofu files, to fully simulate working in .tf
files:
# Let's look at the value of the first variable
> var.one_digit
"5"
# Let's look at the value of the second variable
> var.two_digit
"50"
# Find greatest
> max(var.one_digit, var.two_digit)
50
# Find sum
> sum([var.one_digit, var.two_digit])
55
# The function below appends a value to a string, preserving the leading zero for two-digit values (00, 01, 02, .., 99)
# Try for a single digit number
> "yay-10${var.one_digit >= 0 && var.one_digit < 10 ? join("",["0",tostring(var.one_digit)]) : var.one_digit}"
"yay-1005"
# Try for a double digit number
> "yay-10${var.two_digit >= 0 && var.two_digit < 10 ? join("",["0",tostring(var.two_digit)]) : var.two_digit}"
"yay-1050"
# Read the contents of a text file (uses a relative path to files by default)
> file(text)
"Hello!"
You can even pass it via a pipe to stdin, for example:
echo "max(1, 2, 3)" | tofu console
3
# Don't forget to escape special characters with a backslash
echo "base64encode(\"Hello World\")" | tofu console
"SGVsbG8gV29ybGQ="