Skip to content

Function lookup()

📝 Description

The lookup function retrieves the value of a single element from a map, given its key. If the key does not exist, it returns a default value instead of crashing your Terraform run.

Use Case: Setting environment-specific values (like instance types or AMIs) where you might not have a specific value for every single environment.


💻 Syntax

Terraform

lookup(map, key, default)

💡 Examples

1. Basic Usage:

variable "instance_types" {
  default = {
    "prod" = "t3.large"
    "dev"  = "t3.micro"
  }
}

# Result: "t3.micro"
output "selected_type" {
  value = lookup(var.instance_types, "dev", "t2.nano")
}

2. Using the Default Value:

If the key "test" is missing, Terraform won't fail; it will just use the fallback.

# Result: "t2.nano" (because "test" key is not in the map)
output "fallback_type" {
  value = lookup(var.instance_types, "test", "t2.nano")
}

3. Practical Scenario: Tagging

Ensuring a resource always has a "Project" tag, even if it wasn't explicitly defined in a specific map:

locals {
  custom_tags = {
    Owner = "Ivan"
  }

  project_name = lookup(local.custom_tags, "Project", "Internal-Wiki")
}

⚠️ Common Pitfalls

  • lookup only works with maps. If you try to use it on a list, Terraform will throw an error.

  • If you know the key exists and don't want a default, you can use the map["key"] syntax, but lookup is much safer for dynamic code.


  • [[keys]] — Get all available keys in the map.

  • [[element]] — Similar to lookup, but for lists.

  • Official HashiCorp Docs