DEV Community

Ana Carolina Manzan
Ana Carolina Manzan

Posted on

Boost your IaC development with terraform console

Hi devs!

If you are a terraform user, you've likely already used some of the built-in functions of it, like concat, map or format.

Whilst using some of these functions, have you ever asked yourself which would be the output of the function or even thought about testing it before incorporating it to your codebase? Well, I did it, and in this post I'll show you how you can test these functions in a practical way using terraform CLI itself!

The terraform console command

The terraform console command offers us an interactive console to which we can use to test built-in functions.

To begin with the testing, start your terminal type terraform consoleand press enter. After executing the command, the console prompt will be loaded right away. We will start by testing the function max(8,5,42,12) with a list of values like we can see in the example below:

Image description

In this simple test, we could validate that using max function with 8, 5, 42 and 12 as inputs, we will get the number 42 as the ouput considering it is the highest number in the list.

I'll bring another test scenario here using split(“,”, “Testing,terraform,functions”). This function is responsible for splitting our text at each comma found and transforming it in a word list, as we can check in the following image:

Image description

In short: in addition to the output, terraform console also bring information about the output format as we may check above with the list represented by tolist([...]).

Interacting with files

More than just testing functions, we can also use terraform console to interact with Terraform files.

To illustrate it, I created a file called variables.tf right in the directory in which I'm performing my tests and included a variable called cidr in it.

Image description

I set a default value of 10.1.0.0/16 for this variable, because I want to use it to calculate subnet addresses; To calculate the addresses I will use the cidrsubnet function.

I would like to provide an example of a different usage of terraform console command. To do this, I will use it by adding a pipe after calling the desired function:

echo '[for i in range(1, 5) : cidrsubnet(var.cidr, 8, i)]' | terraform console

After running this code, we will obtain the results:

Image description

Conclusion

Terraform console can become a valuable tool in our daily basis as our infrastructure code base grows. It can be a powerful ally whenever we need to ensure that the code we are developing will produce the results we expect.

I hope this content can contribute to your journey, and if you enjoyed it please leave a comment or contact me through LinkedIn.

See ya'll! 👋

Top comments (0)