3 Ways to Reference Variables in Terraform

Variables can pass data into a Terraform configuration and can be used to parameterize the configuration.

They allow you to reuse the same configuration in different environments or for different purposes without hard-coding the values.

To run a Terraform configuration that references variables, your code will need to provide the values for those variables either by defining them in a TFVARS file or by passing them in as command-line arguments.

TFVARS

TFVARS is short for Terraform variables. Variables are a way to pass data into a Terraform configuration and can be used to parameterize the configuration. They can be defined in a file with a .tfvars extension or can be passed in as command-line arguments when running Terraform.

To use a TFVARS file, you will to pass the path to your TFVARS file as an argument to the terraform apply command:

terraform apply -var-file=path/to/vars.tfvars

Var Flag

Alternatively, you can use the -var flag to set the value of a single variable:

terraform apply -var 'region=us-east-2'

Set Variables in Configuration

You can also set variables in a Terraform configuration file using the variable block:


variable "region" {
default = "us-east-2"
}

It’s also possible to set variables using environment variables, but this is generally not recommended because it can make it challenging to understand the values being used in the configuration.

Processing…
Success! You're on the list.

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.