Environment Variables
An environment variable is a value set in the shell before Terraform runs. Terraform reads some of them to fill variables and credentials.
Set a variable from the shell
The variable environment takes the value prod.
export TF_VAR_environment="prod"
terraform planPass AWS credentials
These two values let the AWS provider sign requests.
export AWS_ACCESS_KEY_ID="test"
export AWS_SECRET_ACCESS_KEY="test"A flag beats the shell
The -var flag wins over TF_VAR_ for the same variable.
TF_VAR_environment="prod" terraform apply -var="environment=dev"Example
# main.tf
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
variable "environment" {
type = string
default = "dev"
}
resource "local_file" "hello" {
content = "Hello from the ${var.environment} environment."
filename = "${path.module}/hello-${var.environment}.txt"
}
# commands
export TF_VAR_environment="prod"
terraform init
terraform apply -auto-approve
cat hello-prod.txtKey points
- TF_VAR_ sets a variable. The name after the prefix must match the variable name.
- A value from the shell beats a default. The -var flag beats TF_VAR_.
- Provider credentials come from the environment too. AWS reads AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Secrets belong in the environment, not in code. Code is shared, and the shell is not.
- Export the value in the same shell that runs Terraform. A new shell starts empty.
The shell value prod fills the variable, so no file or flag is needed. The default dev is ignored. The same trick carries credentials, so secrets never sit in the code.
Note
a value set with TF_VAR_ still appears in plan output. It is not hidden.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How do you set the variable named region from the shell?