Terraform console is a tool that provides Terraform to evaluate expressions or debug resources in a state in an interactive way. It’s a very useful ally when we are working with Terraform functions and want to test which is the result before applying, or when you are working with resources or modules for which we are not sure which are outputs and you want to debug what is returned.
To use Terraform Console we just need to write the command.
If we do not have a state in the folder where the terminal in which the command was run is located, it will work as a simple interpreter. On the other hand, if a state is found or one in the cloud is loaded, then it will read it to have the data of the resources at our command and start the interpreter.
Let’s make an example of creating a VPC. Suppose we want to create a VPC with 4 subnets in a dynamic way. For this, we are going to initiate Terraform Console and make use of terraform functions.
First, we will use a function called “cidrsubnet” (https://developer.hashicorp.com/terraform/language/functions/cidrsubnet), that given the IP of the VPC, the additional number of Bits and the subnet number that we want, it returns the CIDR block of the subnet. Let’s try with the following example.
As we can see if we change the subnet number the cidr block increases, this can be made a little more dynamic using a range and a for. We could get the number of subnets we want, let's see what happens with 4 subnets.
And that's it, it returns our 4 subnets ready to be used in a resource or a module. Using the vpc module as an example, we would have to add something like this.
And that's it, when we apply we will have our vpc with 4 public and 4 private subnets. In this way, we can use and test any terraform function and make sure that the results we want are really what we expected.
Another good function of the Terraform console (one that I use the most) is to debug our resources that are already in the cloud. A quick example would be to see the values that data brings to us.
Now, if we go to the Terraform console and ask for the same data in the following way we will receive this.
Like this, we can bring the data of all the resources, modules, and terraform data to see their values.
It’s very useful when the infrastructure becomes very large and you want to see the exact values that are being passed to other resources quickly without having to go through the code.
If you want to know more about Terraform, we suggest going check Terraform Workspaces
If you are interested in learning more about our #TeraTips or our blog's content, we invite you to see all the content entries that we have created for you and your needs. And subscribe to be aware of any news! 👇