Course contentsShow
← Cloud and Infrastructure
Lesson 761 of 2,98914. Terraform FundamentalsFree lesson

Environment Variables for Input

Use TF_VAR_ prefixed environment variables to set Terraform input values.

Environment Variables for Input

What you'll learn: How to supply Terraform input variable values using special environment variables instead of files or command-line flags.


The Core Idea

Terraform supports a naming convention that lets you set input variable values through your shell's environment variables. Any environment variable prefixed with TF_VAR_ followed by the variable name will automatically populate that Terraform variable.

For example, if you've declared a variable named instance_type, you can set it by exporting TF_VAR_instance_type in your shell.

Why Use Environment Variables?

This approach is particularly useful in automated environments like CI/CD pipelines, containerized builds, or local development where you don't want to commit sensitive values to version control. Instead of passing values via command-line flags or .tfvars files, you can configure them in your execution environment once and forget about them.

Think of it like this: Instead of handing Terraform a written note (a file) or whispering instructions (CLI flags) every time, you're setting up a bulletin board (environment variables) that Terraform automatically checks when it needs values.

Syntax Pattern

export TF_VAR_<variable_name>=<value>

The variable name after TF_VAR_ must exactly match your declared variable name in your configuration. If you have a variable region, you'd use TF_VAR_region.

For complex types like lists or maps, you'll need to use HCL syntax in the environment variable value (though this can get unwieldy for complex structures).

Precedence Note

Environment variables have lower precedence than explicit -var flags and .tfvars files, so they act as convenient defaults that can be overridden when needed.

Key Takeaway:
Use TF_VAR_ prefixed environment variables to set Terraform input values from your shell environment—ideal for automation, secrets, and developer-specific configurations without touching configuration files.