A nested attribute may or may not exist, and `lookup` or index errors break the plan. How do you write resilient expressions?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → Optional data causes "Invalid index" or "attribute not found" errors.
What I'd do →
- Use
try()for fallbacks,can()for validations,coalesce()for first non-null andlookup()for map keys. - Prefer typed optional object attributes over defensive expressions.
locals {
port = try(var.app.port, 8080)
log_days = lookup(var.retention, var.environment, 30)
region = coalesce(var.region_override, data.aws_region.current.name)
}
Why → These make intent explicit, but try() can mask real typos, so I limit it to genuinely optional values.
Interview tip → If every line has try(), the variable's type is too loose.
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?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA 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`?Advanced