for-loopdynamicterraformtuples

Terraform dynamically create a tuple


Here is the challenge:

I have an iterated for-each loop to create a bunch of elements in a list:

test_count = 90
test_items = [for i in range(local.test_count) : format("test%02s", i+1)]

What I need to do is to dynimcally create a local tuple that looks like the below:

custom_items = {
    test01 = {
      name      = concat("test01", "shared value")
    }
    test02 = {
      name      = concat("test02", "shared value")
    }
  }

This is because the test01 component is used as a key later on for calling dynamically created modules.

However, I am not sure if or how one can dynamically create a list.

Obviously there will be a for_each loop or a for i in etc. in it, but I am not sure how to create the list, to be able to reference it later on.


Solution

  • Iterate over test_items to create the desired object:

    locals {
      test_count = 90
      test_items = [for i in range(local.test_count) : format("test%02s", i + 1)]
      custom_items = {
        for item in local.test_items :
        item => {
          name = format("%s%s", item, "shared value")
        }
      }
    }
    
    > local.custom_items
    {
      "test01" = {
        "name" = "test01shared value"
      }
      "test02" = {
        "name" = "test02shared value"
      }
      "test03" = {
        "name" = "test03shared value"
      }
      "test04" = {
        "name" = "test04shared value"
      }
      ...
    }