Explain conditional expressions and functions like `try` and `coalesce` for handling optional values.

5 minintermediateterraformexpressionsfunctions

Quick Answer

Terraform's conditional expression `condition ? true_val : false_val` is the ternary operator for HCL, commonly used for feature toggles (e.g., `count = var.enabled ? 1 : 0`) or picking a value based on environment. `try(...)` evaluates a list of expressions and returns the first one that doesn't error — handy for optional attributes that may not exist on every object. `coalesce(...)` returns the first non-null/non-empty argument, useful for "use this value, or fall back to that default." Together they let modules gracefully handle optional inputs without verbose null-checking.

Detailed Answer

HCL has several expression-level features for handling optional or conditional values without verbose null-checking logic, since Terraform configuration has no if statements in the imperative sense — everything is an expression.

Conditional (ternary) expressions

resource "aws_instance" "web" {
  count         = var.create_instance ? 1 : 0
  instance_type = var.environment == "prod" ? "m5.large" : "t3.micro"
}

condition ? true_val : false_val is HCL's ternary operator. Extremely common for feature toggles (create a resource only if a flag is set) and for picking a value based on environment, without needing separate resource blocks per case.

try(...)

locals {
  # Some objects in the list may not have an "owner" attribute at all.
  owner = try(var.config.owner, "unassigned")
}

try() evaluates each argument in order and returns the first one that doesn't produce an error (as opposed to the first one that's merely non-null). It's especially useful when accessing a potentially-missing attribute on an object/map where a plain lookup would error out entirely rather than just returning null.

coalesce(...)

locals {
  # Use an explicit override if given, otherwise fall back to a computed default.
  instance_name = coalesce(var.custom_name, "${var.project}-${var.environment}")
}

coalesce() returns the first argument that is not null and not an empty string, ideal for "use this value if provided, otherwise fall back to a default" — a very common pattern for optional module inputs.

Why these matter together

Modules frequently need to support optional inputs gracefully — a variable that might be null, an object that might be missing a field, a value that should have a sensible fallback. try, coalesce, and conditional expressions let module authors handle these cases declaratively and concisely, instead of forcing every caller to always supply every possible value explicitly.