Search code examples
terraformf5

how to create multiple dynamic block entries from a list pulled from a map


i have varible which is a map

variable ltm-datagroups = {
  "0" = {
    datagroup_name      = "abc"
    datagroup_type      = "ip"
    datagroup_addresses = ["10.0.0.0/8", "172.16.1.0/24"]
  }
  "1" = {
    datagroup_name      = "def"
    datagroup_type      = "ip"
    datagroup_addresses = ""
  }
}

i pass this map to a module, which looks up the value for "datagroup_addresses". from that i want to create multiple entries, based on length of the list.

resource "bigip_ltm_datagroup" "datagroup" {
  for_each = var.ltm-datagroups
  name     = lookup(var.ltm-datagroups[each.key], "datagroup_name")
  type     = lookup(var.ltm-datagroups[each.key], "datagroup_type")
  dynamic "record" {
    for_each = lookup(var.ltm-datagroups[each.key], "datagroup_addresses") != "" ? ["${length(lookup(var.ltm-datagroups[each.key], "datagroup_addresses"))}"] : []
    content {
      name = lookup(var.ltm-datagroups[each.key], "datagroup_addresses")
    }
  }
}

this is the error i see

Error: Incorrect attribute value type

  on modules/ltm-datagroup/main.tf line 8, in resource "bigip_ltm_datagroup" "datagroup":
   8:   name = lookup(var.ltm-datagroups[each.key], "datagroup_addresses")
    |----------------
    | each.key is "0"
    | var.ltm-datagroups is object with 2 attributes

Inappropriate value for attribute "name": string required.


Error: Incorrect attribute value type

  on modules/ltm-datagroup/main.tf line 8, in resource "bigip_ltm_datagroup" "datagroup":
   8:   name = lookup(var.ltm-datagroups[each.key], "datagroup_addresses")
    |----------------
    | each.key is "1"
    | var.ltm-datagroups is object with 2 attributes

Inappropriate value for attribute "name": string required.

i am stuck on the last part. how to run the dynamic block multiple times? while iterating through the entries in the list?


Solution

  • Not sure I fully understand your desired outcome, but if you want to create record dynamically, then it should be:

      dynamic "record" {
        for_each = lookup(var.ltm-datagroups[each.key], "datagroup_addresses") != "" ? toset(lookup(var.ltm-datagroups[each.key], "datagroup_addresses")) : []
        content {
          name = record.value
        }
      }