Terraform Environment Variables
Environment variables provide a way to set and manage configuration values outside of your Terraform code. They are particularly useful for storing sensitive information such as API keys and passwords without hardcoding them into your Terraform files.
Introduction to Environment Variables in Terraform
Environment variables are key-value pairs that can be accessed by applications during runtime. In Terraform, they serve as a way to:
- Pass sensitive information securely
- Override default variable values
- Configure provider behavior
- Control Terraform's execution environment
Using environment variables allows you to keep your configuration flexible and helps maintain good security practices by avoiding hardcoded secrets in your codebase.
Terraform Built-in Environment Variables
Terraform recognizes several built-in environment variables that control its behavior:
Core Terraform Environment Variables
Variable Name | Purpose |
---|---|
TF_LOG | Sets the logging verbosity (TRACE, DEBUG, INFO, WARN, ERROR) |
TF_LOG_PATH | Specifies a file where logs should be written |
TF_INPUT | Disable/enable interactive prompts (0/1) |
TF_VAR_name | Set values for Terraform variables |
TF_CLI_ARGS | Specify additional CLI arguments |
TF_DATA_DIR | Specifies the location of Terraform's data files |
Provider-Specific Environment Variables
Many providers have their own environment variables for authentication:
- AWS:
AWS_ACCESS_KEY_ID
,AWS_SECRET_ACCESS_KEY
- Azure:
ARM_CLIENT_ID
,ARM_CLIENT_SECRET
- Google Cloud:
GOOGLE_CREDENTIALS
,GOOGLE_PROJECT
Setting Terraform Variables with Environment Variables
One of the most common uses of environment variables in Terraform is to set input variables. Terraform will automatically load any environment variable that begins with TF_VAR_
as a variable value.
Let's look at how this works: