Interview Prep/Terraform/Resources Variables and Expressions

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 →

  1. Use try() for fallbacks, can() for validations, coalesce() for first non-null and lookup() for map keys.
  2. 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.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions