0
0
Terraformcloud~3 mins

Why Environment variables (TF_VAR_) in Terraform? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change your cloud setup without touching a single line of code?

The Scenario

Imagine you have to configure your cloud infrastructure by typing every setting directly into your Terraform files or commands each time you deploy.

For example, you want to change the server size or region for different projects, so you edit the files manually every time.

The Problem

This manual way is slow and risky.

You might forget to change a value, causing errors or deploying wrong resources.

It's also hard to share configurations safely without exposing sensitive data.

The Solution

Using environment variables with the TF_VAR_ prefix lets you set values outside your code.

This means you can easily switch settings by changing environment variables, without touching your Terraform files.

It keeps your configurations clean, safe, and flexible.

Before vs After
Before
terraform apply -var 'region=us-east-1' -var 'size=small'
After
export TF_VAR_region=us-east-1
export TF_VAR_size=small
terraform apply
What It Enables

You can quickly and safely customize your infrastructure settings across different environments without changing your code.

Real Life Example

A developer working on multiple projects can set environment variables for each project's cloud region and server size, then run the same Terraform commands without editing files.

Key Takeaways

Manual configuration is slow and error-prone.

TF_VAR_ environment variables let you separate settings from code.

This makes infrastructure deployment safer, faster, and more flexible.