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:

TF_VAR_region=us-east-2

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.

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.