How to Use the Lookup Function in Terraform: Syntax and Examples
In Terraform, the
lookup function retrieves a value from a map by a given key and returns a default value if the key is missing. Use it as lookup(map, key, default) to safely access map elements without errors.Syntax
The lookup function has three parts:
- map: The map to search in.
- key: The key to find in the map.
- default: The value to return if the key is not found.
This helps avoid errors when a key might be missing.
terraform
lookup(map, key, default)
Example
This example shows how to use lookup to get a color from a map. If the key is missing, it returns a default color.
terraform
variable "colors" { type = map(string) default = { red = "#ff0000" green = "#00ff00" blue = "#0000ff" } } output "color_red" { value = lookup(var.colors, "red", "#000000") } output "color_yellow" { value = lookup(var.colors, "yellow", "#ffff00") }
Output
color_red = "#ff0000"
color_yellow = "#ffff00"
Common Pitfalls
Common mistakes include:
- Not providing a default value, which causes errors if the key is missing.
- Using
lookupon a non-map type. - Confusing
lookupwith direct map access, which fails if the key is absent.
Always provide a default to avoid runtime errors.
terraform
/* Wrong: No default, causes error if key missing */ output "color_missing" { value = lookup(var.colors, "purple") } /* Right: Provide default to avoid error */ output "color_missing_safe" { value = lookup(var.colors, "purple", "#800080") }
Quick Reference
lookup(map, key, default)
map: Map to searchkey: Key to finddefault: Value if key missing
Use to safely get map values with fallback.
Key Takeaways
Use lookup(map, key, default) to safely get values from maps in Terraform.
Always provide a default value to avoid errors if the key is missing.
lookup works only on maps; using it on other types causes errors.
Direct map access fails if the key is absent; lookup prevents this.
Use lookup to write more robust and error-proof Terraform code.