Variables, outputs and locals
Terraform · 13 questions
Short notes
Key idea
Variables are a module's inputs, outputs its results, and locals named values computed inside it. Together they keep configs reusable and free of repeated literals.
Syntax
variable "env" {
type = string
description = "dev or prod"
validation {
condition = contains(["dev", "prod"], var.env)
error_message = "env must be dev or prod"
}
}
locals {
prefix = "shop-${var.env}"
labels = { team = "data", env = var.env }
}
output "bucket_url" { value = google_storage_bucket.raw.url }
Values come from terraform.tfvars, -var flags, TF_VAR_env environment variables or defaults.
Example
dev.tfvars has env = "dev"; prod.tfvars has env = "prod". terraform apply -var-file=prod.tfvars creates shop-prod-raw with prod labels, from the same code.
Traps
- Secrets in
.tfvarsfiles end up in Git; keep them out or use a secret manager. sensitive = truehides a value in output, but it's still stored in state.- Locals can't be overridden from outside; use a variable when callers need control.
- Validate inputs so mistakes fail at plan time, not halfway through apply.
Want the full lesson with step-by-step examples, a project and a certificate? Terraform course, ₹120 →
- Question 1easy
How do you read the value of a variable declared as
variable "region" { ... }? - Question 2medium
variable "env" { type = string }has no default. What happens when you runterraform planwithout giving it a value? - Question 3easy
Which type fits
["raw", "staging", "marts"]? - Question 4medium
What's the benefit of a
validationblock onenv? - Question 5hard
envhasdefault = "dev",terraform.tfvarssetsenv = "test", and you runterraform plan -var="env=prod". Which value is used?
Variables, outputs and locals
Variables, outputs and locals
Variables, outputs and locals
Variables, outputs and locals
Variables, outputs and locals
8 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.