Search code examples
terraform

How does Terraform do implicit conversion of an empty map in a conditional expression?


Ran into something weird:

locals {
  outer_map = {
    inner_map = {
      key = "value"
    }
  }
}

resource "random_string" "default" {
  length = lookup(local.outer_map, "inner_map", {}) != {} ? 4 : 2
}

This works fine, length is 4.

locals {
  outer_map = {}
}

This is also fine, length is 2 as expected. But:

locals {
  outer_map = true ? {
    inner_map = {
      key = "value"
    }
  } : {}
}

This throws an error:

╷
│ Error: Invalid function argument
│
│   on test.tf line 10, in resource "random_string" "default":
│   10:   length = lookup(local.outer_map, "inner_map", {}) != {} ? 4 : 2
│     ├────────────────
│     │ while calling lookup(inputMap, key, default...)
│
│ Invalid value for "default" parameter: the default value must have the same type as the map elements.
╵

I'm aware of the type conversions inside a conditional expression, but I can't fathom how it would convert an empty map and a map of a map into something that is incompatible with an empty map. Is it intended behavior that the error should be thrown? Is it a bug in Terraform?


Solution

  • In case anyone else stumbles upon this, here's the answer straight from HashiCorp: https://github.com/hashicorp/terraform/issues/35662