terraform: Using for_each over tuples

2 min read | by Jordi Prats

Let's imagine we have the following data structure:

locals {
  queries = [
    {
      query  = "SELECT version()"
      engine = "postgresql"
    },
    {
      query  = "SELECT * FROM v$version"
      engine = "oracle"
    },
    (...)
  ]
}

If we want to use just some of the items on a resource we can use for_each through the resulting array of filtering the objects using a for:

for_each = [ for item in local.queries: item if item.engine == "postgresql" ]

The problem is that terraform won't allow you to use a tuple of elements on a for_each:

 Error: Invalid for_each argument
 
   on main.tf line 75, in resource "null_resource" "sql_apply":
   75:   for_each = [ for item in local.queries: item if item.engine == "postgresql" ]
     ├────────────────
      local.queries is tuple with 10 elements
 
 The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.

To be able to workaround this we can create an ad-hoc map with the object we want to use:

for_each = { for item in local.queries: item.query => item if item.engine == "postgresql" }

The only consideration to make is that the selected key (on the example item.query) must be unique


Posted on 22/06/2021