TECHNOLOGIESTieInn Technologies

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 .tfvars files end up in Git; keep them out or use a secret manager.
  • sensitive = true hides 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Variables, outputs and locals

  1. Question 1easy

    How do you read the value of a variable declared as variable "region" { ... }?

  2. Variables, outputs and locals

  3. Question 2medium

    variable "env" { type = string } has no default. What happens when you run terraform plan without giving it a value?

  4. Variables, outputs and locals

  5. Question 3easy

    Which type fits ["raw", "staging", "marts"]?

  6. Variables, outputs and locals

  7. Question 4medium

    What's the benefit of a validation block on env?

  8. Variables, outputs and locals

  9. Question 5hard

    env has default = "dev", terraform.tfvars sets env = "test", and you run terraform plan -var="env=prod". Which value is used?

8 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.