How to Use Terraform Environment Variables

Terraform environment variables are used to set values that should not be committed to version control.

They can be used to pass in sensitive information, such as access keys, or to set environment-specific values, such as the name of an S3 bucket.

Terraform allows us to set environment variables to be used in your configuration using the TF_VAR_name syntax, where the name is the name of the variable. For example:


You can then reference the value of the region variable in your configuration using the var.region syntax.

resource "aws_instance" "web" {
ami = var.ami
instance_type = var.instance_type
region = var.region

It’s important to note that environment variables have a lower precedence than variables defined in a TFVARS file or using the -var flag. This means that if you set the value of a variable using an environment variable and also define it in a TFVARS file, the value from the TFVARS file will be used.

You can also set environment variables using the export command in your terminal, but these will only be available for the current session.

Success! You're on the list.

Leave a Comment

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