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.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?AdvancedA security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?Intermediate