Interview Prep/Terraform/Resources Variables and Expressions

How do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?

BeginnerScenarioResources Variables and Expressions
Answer

Situation read → You want to fail early with a clear message.

What I'd do → Add a validation block to the variable.

variable "environment" {
  type = string
  validation {
    condition     = contains(["dev", "stage", "prod"], var.environment)
    error_message = "environment must be one of: dev, stage, prod."
  }
}

Why → Validation runs at plan time before any API call, so bad input never reaches the cloud.

Interview tip → Since Terraform 1.9, validation conditions can reference other variables and data sources, not just the variable itself.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions