How to set a variable on terraform using environment variables

2 min read

To set a value for a variable on terraform we have several ways of doing it:

  • Using the -var command line option.
  • In variable definitions (.tfvars) files. The files named terraform.tfvars, terraform.tfvars.json or any files with names ending in .auto.tfvars or .auto.tfvars.json will be loaded automatically, but they can also be loaded using the -var-file option.
  • As environment variables.

To load a variable using an environment variable it will have to be named using the TF_VAR prefix. For example, to set the region variable we will have to set the TF_VAR_region environment variable:

export TF_VAR_region=us-west-1

We can also set lists and maps using the usual syntax, we just need to make sure they are loaded properly into the variable (not interpreted by the shell itself):

export TF_VAR_list='[1,2,3]'
export TF_VAR_map='{ foo = "bar", baz = "qux" }'

Using these variables to set values can be a double-edged sword, if these variables are not set as code somewhere else we would be breaking the Infrastructure as Code since not everything is defined as code thus making it impossible to rebuild de infrastructure.

Posted on 03/01/2022