0
0
TerraformHow-ToBeginner · 3 min read

How to Use the try Function in Terraform for Safe Expressions

In Terraform, the try function evaluates multiple expressions in order and returns the first one that does not produce an error. Use try(expr1, expr2, ...) to safely handle optional or uncertain values without breaking your configuration.
📐

Syntax

The try function takes one or more expressions as arguments. It evaluates each expression from left to right and returns the first expression that succeeds without error. If all expressions fail, it returns the error from the last expression.

  • expr1, expr2, ...: Expressions to try in order.
terraform
try(expr1, expr2, ...)
💻

Example

This example shows how to use try to get a value from a map safely. If the first key does not exist, it tries the second key, avoiding errors.

terraform
variable "config" {
  type = map(string)
  default = {
    primary = "value1"
    # secondary key might be missing
  }
}

output "safe_value" {
  value = try(var.config["primary"], var.config["secondary"], "default_value")
}
Output
safe_value = "value1"
⚠️

Common Pitfalls

Common mistakes when using try include:

  • Not providing a fallback value, which can cause errors if all expressions fail.
  • Using try with expressions that have side effects or expensive computations.
  • Confusing try with conditional expressions; try handles errors, not just true/false conditions.
terraform
/* Wrong: No fallback, may error if all fail */
output "value" {
  value = try(var.missing_key1, var.missing_key2)
}

/* Right: Provide fallback to avoid errors */
output "value" {
  value = try(var.missing_key1, var.missing_key2, "fallback")
}
📊

Quick Reference

Use try to safely evaluate multiple expressions and avoid runtime errors in Terraform configurations. Always include a fallback value to ensure stability.

FeatureDescription
PurposeReturn first successful expression without error
ArgumentsOne or more expressions to try in order
ReturnsValue of first successful expression or error of last
Use CaseHandle optional or missing values safely
Best PracticeAlways provide a fallback expression

Key Takeaways

The try function returns the first expression that does not error.
Always include a fallback value to prevent configuration failures.
Use try to handle optional or missing values safely in Terraform.
try evaluates expressions left to right and stops at the first success.
Avoid using try with expressions that have side effects or are costly.