How can I use chucklist to create a map of chunked arrays?

Viewed 130

I have this set:

variable "test" {
  type        = set(string)
  default = [
    "asia-east1-a",
    "asia-east1-b",
    "asia-east1-c",
    "asia-east2-a",
    "europe-west2-a",
    "europe-west2-b",
    "europe-west2-c",
    "europe-west3-a",
  ]
}

I want to divide this programmatically into sub-arrays (big table instances only support 4 clusters per instance for example and I want to config that programmatically).

I want a map that looks like this (that the google_bigtable_instance resource can loop over and use a dynamic block on the lists for cluster{} config)

locations = {
    location1 = ["asia-east1-a", "asia-east1-b", "asia-east1-c", "asia-east2-a"]
    location2 = ["europe-west2-a", "europe-west2-b", "europe-west2-c", "europe-west3-a"]
    etc
}

Using chunk list throws an error: The key expression produced an invalid result: string required.

// locals
  test = {
    locations = {
      for zone in toset(chunklist(var.test, 4)) : zone => {
        zone = zone
      }
    }
  }

I don't want to use lists anywhere because I want to be able to remove an item from the middle of var.test and not have the order cause terraform to destroy/recreate other items.

1 Answers

If you literally want to transform to

locations = {
  location1 = ["asia-east1-a", "asia-east1-b", "asia-east1-c", "asia-east2-a"]
  location2 = ["europe-west2-a", "europe-west2-b", "europe-west2-c", "europe-west3-a"]
}

and also want to use chunklist (would recommend a regexp filter possibly with grouping instead as it would be safer and futureproof, but chunklist is fine as long as you will always have four locations in each subset), then you can alter your for expression like the following:

# for expression within map constructor
# lambda iterator variable 'zones' is assigned first list of four strings with locations and 'index' is assigned first index 0
locations = { for zones, index in toset(chunklist(var.test, 4)) : "location${index + 1}" => zones }
# 'locations1' for key and ["asia-east1-a", "asia-east1-b", "asia-east1-c", "asia-east2-a"] for value

You should also be able to see from the comments above what the behavior will be on future iterations. The return from the above for expression will be exactly the value you are looking for in the question and assigned to the variable locations.

Related