How to Use Environment Variables in Terraform for Configuration
In Terraform, you can use environment variables by prefixing them with
TF_VAR_ to set input variables or by using provider-specific environment variables for authentication. Terraform automatically reads these variables during execution, allowing you to configure your infrastructure without hardcoding sensitive data.Syntax
Terraform reads environment variables in two main ways:
- Input variables: Use environment variables with the prefix
TF_VAR_followed by the variable name to set Terraform input variables. - Provider authentication: Providers like AWS or Azure use specific environment variables (e.g.,
AWS_ACCESS_KEY_ID) for credentials.
This lets you keep sensitive data out of your Terraform files.
bash
export TF_VAR_region="us-west-2" export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key"
Example
This example shows how to use an environment variable to set a Terraform input variable called region and configure the AWS provider.
hcl
variable "region" { description = "AWS region" type = string default = "us-east-1" } provider "aws" { region = var.region } resource "aws_s3_bucket" "example" { bucket = "my-example-bucket-12345" acl = "private" }
Output
Terraform will create an S3 bucket in the region set by the environment variable TF_VAR_region or use the default us-east-1 if not set.
Common Pitfalls
Common mistakes when using environment variables in Terraform include:
- Not prefixing input variable environment variables with
TF_VAR_, so Terraform ignores them. - Setting environment variables after running
terraform initorterraform planwithout restarting the shell session or reloading the environment. - Exposing sensitive data in environment variables without proper security.
bash
Wrong (ignored by Terraform): export region="us-west-2" Right (recognized by Terraform): export TF_VAR_region="us-west-2"
Quick Reference
- Input variables: Use
TF_VAR_variable_nameto set variables. - Provider credentials: Use provider-specific environment variables like
AWS_ACCESS_KEY_ID. - Check variables: Run
terraform consoleand typevar.variable_nameto see current values.
Key Takeaways
Prefix environment variables with TF_VAR_ to set Terraform input variables.
Use provider-specific environment variables for authentication credentials.
Always export environment variables before running Terraform commands.
Avoid hardcoding sensitive data in Terraform files by using environment variables.
Verify variable values with terraform console for troubleshooting.