How to use the each.key value as a variable name

I want to pass in a list of strings that are table names I’m going to create in a module. The table definitions will be in a file in the subfolder where the module is. So my module will look something like this:

module "parquet_tables" {
    source    = "./create_table"
    table_names = [ "tab1", "tab2" ]
    providers = {
        aws 
  }
}

Then in a file in the subfolder I will have definitions in locals for each table:

locals {
  tab1 = {
    table_name = "table 1"
    table_description = ....
    s3_location = "s3://....
    database_name ="dbname"
.
.  }
}

Then in my create_table I want to iterate through the table_names list and create each table with for_each:

resource "aws_glue_catalog_table" "tablex" {
  provider = aws
  for_each = toset(var.table_names)
  name          = local.${each.key}.table_name
  database_name = local.${each.key}.database_name

This doesn’t work of course - it tells me an attribute name is required after the “local.” How can I get that string value of each table name I pass in as a table name to reference the local value of the same name?

1 Like

Did you ever manage to figure this out?

It is impossible, Terraform doesn’t support dynamic access to arbitrary locals.

Though, if you refactored it so it was instead dynamic access to keys within a map/object value, that was itself stored in a single local, that could work.

You should be able to do something like this (not tested):

locals {
  tables = {
    "tab1" = {
      table_name = "tab1"
      table_description = "..."
      s3_location = "s3://..."
      database_name ="dbname"
    }
    "tab2" = {
      # ...
    }
  }
}

resource "aws_glue_catalog_table" "tablex" {
  provider = aws
  for_each = toset(var.table_names)
  name          = local.tables[each.key].table_name
  database_name = local.tables[each.key].database_name
}