Before exploring Terraform variables, let’s first understand what variables are.
A variable is simply something whose value can change. Variables are used to avoid hardcoding, improve reusability, enhance readability, and support modular design. Every programming language uses variables and Terraform is no different.
Terraform also supports variables, and they can be categorized in two ways:
- Based on purpose
- Based on value
1. Input Variables
Used to pass values into Terraform from users or external sources.
Example:
variable "region" {
type = string
default = "us-east-1"
description = "AWS region"
}
2. Output Variables
Used to display or export values after terraform apply.
Example:
output "bucket_name" {
value = aws_s3_bucket.demo.bucket
}
3. Local Values (locals)
Used to simplify complex or repeated expressions.
Example:
locals {
env_name = "dev"
}
String Concatenation in Terraform
"${var.env}-bucket"
"${var.env}-bucket-${var.region}"
Terraform Variable Precedence
Terraform loads variables in the following order (LOW to HIGH precedence):
| Precedence | Source | Notes |
|---|---|---|
| 1 | Default values in variables.tf | lowest priority |
| 2 | Environment variables | export TF_VAR_region="us-east-1" |
| 3 | terraform.tfvars | auto-loaded |
| 4 | terraform.tfvars.json | auto-loaded |
| 5 | **.auto.tfvars / *.auto.tfvars.json* | auto-loaded in alphabetical order |
| 6 | -var and -var-file CLI flags | highest priority |
Example Environment Variable
export TF_VAR_env="dev"
✔ Example CLI Variable
terraform apply -var="env=dev"
✔ Example CLI Var File
terraform apply -var-file="dev.tfvars"
Example: Creating an S3 Bucket Using env = dev
variables.tf
variable "env" {
type = string
description = "Environment name"
default = "dev"
}
variable "region" {
type = string
default = "us-east-1"
}
main.tf
provider "aws" {
region = var.region
}
resource "aws_s3_bucket" "demo" {
bucket = "${var.env}-bucket-demo"
}
output "bucket_name" {
value = aws_s3_bucket.demo.bucket
}
terraform.tfvars (optional)
env = "dev"
Run Commands
terraform init
terraform plan
terraform apply
Resulting Bucket Name
dev-bucket-demo


Top comments (0)