Terraform

How to Use Terraform Console Command – Examples

Terraform console command

Have you ever needed a quick and easy way to experiment with Terraform functions and expressions? In this article, we will explore the terraform console command and provide some examples of how to use it.

The Terraform HCL language includes a number of built-in functions you can use in expressions.

Expressions refer to or compute values within a configuration. The simplest expressions are literal values, like "hello" or 5, but the Terraform language also allows more complex expressions such as references to data exported by resources, arithmetic, conditional evaluation, and a number of built-in functions.

Note: Terraform does not support user-defined or ‘custom’ functions.

What is the Terraform console command?

The terraform console command is a part of the Terraform CLI that opens an interactive console where you can experiment with testing interpolations before using them in configurations and interact with any values currently saved in the state.

This command’s primary purpose is to help you understand how Terraform evaluates expressions and functions based on your configuration, making it very useful for testing and debugging.

Terraform console usage & examples

Let’s see some examples.

Testing simple expressions and functions

terraform split expression

Try lower("TEST")

lower terraform

As you can see, you can use the terraform console to test functions and expressions to test the output before modifying your configuration files.

You can also pipe a command directly to the terraform console:

echo 'lower("TEST")' | terraform console

Testing local variables

To test local variables inside the Terraform console, you should have a local variable already defined inside your Terraform configuration.

locals {
   instance_names = ["dev1", "dev2", "qa1", "qa2", "qa3", "prod1", "prod2"]
}

You can access the variable in the Terraform console by prefixing it with local.

> local.instance_names
[
 "dev1",
 "dev2",
 "qa1",
 "qa2",
 "qa3",
 "prod1",
 "prod2",
]

Functions can also be leveraged directly on your local variables there:

> length(local.instance_names)
7

> element(local.instance_names, 4)
"qa3"

> formatlist("Instance %s is running", local.instance_names)
tolist([
 "Instance dev1 is running",
 "Instance dev2 is running",
 "Instance qa1 is running",
 "Instance qa2 is running",
 "Instance qa3 is running",
 "Instance prod1 is running",
 "Instance prod2 is running",
])

You can even use loops and conditional statements directly on your local variable:

> [for instance in local.instance_names: instance if startswith(instance, "qa")]
[
 "qa1",
 "qa2",
 "qa3",
]

Testing for_each loops

You cannot directly test the result of a for_each loop inside of the Terraform console. However, you can achieve the same behavior by leveraging a for loop. Let’s suppose you have the following local variable:

instances = {
       dev1 = {
           instance_type = "t2.micro"
           ami_id        = "dev1ami"
       }
       dev2 = {
           instance_type = "t3.micro"
           ami_id        = "dev2ami"
       }
       dev3 = {
           instance_type = "t3.micro"
           ami_id        = "dev3ami"
       }
 }

Now, let’s replicate the behavior of for_each in the console.

> { for key, value in local.instances : key => value }
{
 "dev1" = {
   "ami_id" = "dev1ami"
   "instance_type" = "t2.micro"
 }
 "dev2" = {
   "ami_id" = "dev2ami"
   "instance_type" = "t3.micro"
 }
 "dev3" = {
   "ami_id" = "dev3ami"
   "instance_type" = "t3.micro"
 }
}

Now let’s take it up a notch to understand who each.key and who is each.value:

> [for key, value in local.instances: format("Each.key is %s. Each.value is %v", key, value)]
[
 "Each.key is dev1. Each.value is {\"ami_id\":\"dev1ami\",\"instance_type\":\"t2.micro\"}",
 "Each.key is dev2. Each.value is {\"ami_id\":\"dev2ami\",\"instance_type\":\"t3.micro\"}",
 "Each.key is dev3. Each.value is {\"ami_id\":\"dev3ami\",\"instance_type\":\"t3.micro\"}",
]

Testing against state and configuration files

If you have a state file for the current configuration, you can also use the console to interact with any values held in the local or remote state. If there is a state file, the console will lock it, meaning no other operations can be performed on it while the console is open. If you are using a remote state, that will be read before evaluating any expressions you enter into the console.

In addition to reading values from any state file, the local configuration files in the current working directory are also taken into account so expressions can be tested against both state and configuration. You will need to run terraform init first on any local configuration to generate the state file.

Here we have a file called main.tf to use for testing:

variable "region" {
  type = map(any)
  default = {
    "uk1" = {
      "region" = "uksouth",
    },
    "uk2" = {
      "region" = "ukwest",
    },
    "us" = {
      "region" = "eastus",
    }
    "us2" = {
      "region" = "eastus2",
    }
  }
}

resource "random_password" "password" {
  length           = 16
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
}

variable "cidr" {
  default = "172.16.0.0/20"
}

With the file in the local working directory, run terraform console.  We can interact with the console and experiment with different functions.

var.region

var region terraform

var.region.us2

var.region.us2

var.cidr

cidrnetmask(var.cidr)

cidrnetmask(var.cidr)

cidrhost(var.cidr, 3)

cidrhost

Terraform will only calculate the values of some resources after terraform apply — the console will show you this.

random_password.password

random_password.password

Once you have finished experimenting with different functions and expressions, hit Ctrl-C or Ctrl-D, or type exit to exit the console.

Can you define variables or modules within the Terraform console?

You cannot define variables or modules within the Terraform console. The Terraform console is primarily a REPL (read->evaluation->print->loop), so it allows you to evaluate Terraform expressions and access the state, variables, locals, and outputs.

To use a specific variable, you must first define it in your configuration.

Modules are a little bit trickier, as you need to first apply the code to access the resources or the outputs if they depend on a particular resource.

Key points

Terraform console is a great way to test logic, check the results of functions for experimentation, and test against your state and configuration files.

We encourage you to explore how Spacelift makes it easy to work with Terraform. If you need help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this.

Manage Terraform Better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.

Start free trial

The Practitioner’s Guide to Scaling Infrastructure as Code

Transform your IaC management to scale

securely, efficiently, and productively

into the future.

ebook global banner
Share your data and download the guide