'Looping through a list of dict and a list within one resource statement

Variable

ip_set = [
  {
    name: "test-ip-set-1"
    ip_list: ["10.0.0.1/32", "10.0.0.1/32"]
  }
]

I want to loop through the ip_set variable and create IP sets per the length of ip_set and loop through ip_list within that dictionary

For e.g.

resource "aws_waf_ipset" "ipset" {
  for_each = {for name, ip_list in var.ip_set: name => ip_list}
  name        = each.value.name

  ip_set_descriptors {
    type  = "IPV4"
    value = each.value.ip_list[ip_list_element_1]
  }
  ip_set_descriptors {
    type  = "IPV4"
    value = each.value.ip_list[ip_list_element_2]
  }

Error

If I do

  ip_set_descriptors {
    type  = "IPV4"
    value = tostring(each.value[*].ip_list)
  }

I get

Invalid value for "v" parameter: cannot convert tuple to string.

FYI. value in ip_set_descriptors needs to be a string and I don't know how many elements are there



Solution 1:[1]

You can use dynamic blocks:

resource "aws_waf_ipset" "ipset" {

  for_each = {for name, ip_list in var.ip_set: name => ip_list}
  name        = each.value.name

  dynamic "ip_set_descriptors" {
    for_each = each.value.ip_list
    content {
      type  = "IPV4"
      value = ip_set_descriptors.value
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin