📘 Terraform Variables
⭐ Input Variables (variable)
Used to pass values into Terraform.
variable "environment" {
default = "dev"
type = string (optional)
description = "name of the environment" (optional)
}Use them as:
var.environment
Warning
If No default value provided then we have to enter value in Interactive Mode
⭐ Local Variables (locals)
Used for internal calculation, concatenation, and reusable values.
locals {
bucket_name = "${var.project}-bucket-${var.environment}"
}Use as:
local.bucket_name
Types of Variables (Based on Value / Type Constraints)
- Primitive Types — string, number, bool
- Complex Types — list(), set(), map(), object(), tuple()
- Special Types — any, null
How to Set Variable Values (Precedence Order)
| Method | Example | Notes |
|---|---|---|
| 1️⃣ Default value in variable block | default = "dev" | Used when no other value is provided |
| 2️⃣ Environment variable | export TF_VAR_environment=stage | Overrides default value |
3️⃣ .tfvars / .auto.tfvars files | environment = "preprod" | Overrides defaults & env vars |
4️⃣ -var / -var-file CLI flag | terraform plan -var="environment=prod" | Overrides everything |