📘 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)

MethodExampleNotes
1️⃣ Default value in variable blockdefault = "dev"Used when no other value is provided
2️⃣ Environment variableexport TF_VAR_environment=stageOverrides default value
3️⃣ .tfvars / .auto.tfvars filesenvironment = "preprod"Overrides defaults & env vars
4️⃣ -var / -var-file CLI flagterraform plan -var="environment=prod"Overrides everything