Lookup, conversion and error handling
Use the right fallback for the problem
lookup reads a key in a map and supplies a default for an absent key. try chooses the first expression that can evaluate without a catchable error. can reports whether a simple expression can evaluate successfully. coalesce selects a non-null, non-empty-string value after finding a compatible common type. These are different contracts; do not use them interchangeably.
Missing keys, nulls and empty strings
Predict each independent console expression:
lookup(tomap({ env = "test" }), "region", "local")lookup(tomap({ env = "test" }), "env", "local")try(tonumber("invalid"), 8080)try(null, "fallback")coalesce(null, "", "service")Results: "local", "test", 8080, null, "service". The default in lookup must be compatible with the map element type; an existing key with a null value does not become an absent key. try does not replace a successful null result. coalesce can fail when no usable argument remains; empty collections are not skipped just because they are empty. Avoid mixing types unintentionally.
Convert and encode data deliberately
Use a conversion when the consumer needs a particular type, not just to silence an error:
tolist(["api", "db"])tomap({ api = 8080, db = 5432 })jsonencode({ enabled = true, count = 2 })jsondecode("{\"enabled\":true,\"count\":2}").countThe first produces a list of strings, the second a map of numbers, the third a JSON string representing an object with enabled and count, and the fourth the number 2. Compare decoded JSON structures rather than depending on object key order. JSON does not retain every Terraform-specific type distinction, so an encode/decode round trip can change the inferred type. Conversion of mixed element types may select a shared type, or fail when none exists.
Normalize optional settings at one boundary
Here a fictional imported settings file is represented by a JSON string. This is a deliberately forgiving demonstration: missing, null or unconvertible optional fields may fall back to defaults. Use this policy only for noncritical settings when callers explicitly accept it. A supplied invalid port in a real infrastructure interface should usually be rejected. The validation below checks that the JSON decodes to an object; it does not validate the full schema.
variable "settings_json" { type = string default = "{\"name\":\"catalog\"}" validation { condition = can(keys(jsondecode(var.settings_json))) error_message = "Settings must be a JSON object." }}locals { raw = jsondecode(var.settings_json) settings = { name = coalesce(try(tostring(local.raw.name), null), "service") port = coalesce(try(tonumber(local.raw.port), null), 8080) }}output "settings" { value = local.settings}Predicted default output: name = "catalog", port = 8080. For an empty JSON object, name = "service", port = 8080. For a supplied numeric string port "9000", port = 9000. Invalid JSON or a JSON array is rejected by the variable validation. Notice that an empty name becomes the fallback because coalesce skips empty strings. An object-shaped name cannot be converted to a string and is also defaulted in this intentionally lenient fixture.
Reject bad input rather than hiding it
When an input controls a real listener, define a contract. This standalone lab requires a decimal integer string in the inclusive range 1–65535:
variable "port_text" { type = string nullable = false default = "8080" validation { condition = can(regex("^[0-9]+$", var.port_text)) && try(tonumber(var.port_text) >= 1 && tonumber(var.port_text) <= 65535, false) error_message = "Port must be a decimal integer from 1 to 65535." }}output "port" { value = tonumber(var.port_text)}Predicted: "8080" is accepted and becomes numeric 8080; "0", "65536", "abc" and "2.5" fail validation. can checks the regular expression; try guards conversions even if boolean operands are evaluated eagerly. This is a numeric range check, not a check that a port is available, permitted or safe to expose.
Do not turn try into general exception handling
A fallback cannot rescue an undeclared top-level reference or malformed expression that Terraform can prove invalid independently of inputs. Unknown is not an error: a value that will be known after apply does not necessarily trigger a fallback. Use try around narrow access or conversion expressions in a normalization boundary, can for a validation predicate, lookup for expected missing map keys, and an explicit type/validation contract for required fields. Do not catch provider API failures with try. Complete the worksheet before proceeding to providers and resources.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lookup, conversion and error handling — knowledge check
Check function evaluation and input contracts.
Which function provides a default for a missing map key?
What does try(null, "fallback") return?
What is coalesce(null, "", "api")?
Can try catch a statically invalid undeclared reference?
Which strict fixture input is acceptable?