Trying to loop through variable with multiple values per key

Trying to loop through dns records but getting the error:

The given “for_each” argument value is unsuitable: the “for_each” argument must be a map, or set of strings, and you have provided a value of type tuple.

variable "dns_records" {
  type = map(any)
  default = {
    "www" = {
      "recordtype" = "A"
      "recorddata" = "152.152.152.152"
    }
    "ftp" = {
      "recordtype" = "CNAME"
      "recorddata" = "www.ftp.org"
    }
    "mail" = {
      "recordtype" = "TXT"
      "recorddata" = "qwertyuiop"
    }
  }
}

locals {
  nestedlist = flatten([
    for n, x in var.dns_records : [
      for t, v in x : {
        name  = n,
        type  = t,
        value = v
      }
    ]
  ])
}

resource "cloudflare_record" "dns_record" {
  for_each = local.nestedlist
  name     = each.value.name
  type     = each.value.type
  value    = each.value.value
  proxied  = false
  ttl      = 1
  zone_id  = "asdfghjklzxcvbnm"
}

Your local.nestedlist has this structure:

[
  {
    "name" = "ftp"
    "type" = "recorddata"
    "value" = "www.ftp.org"
  },
  {
    "name" = "ftp"
    "type" = "recordtype"
    "value" = "CNAME"
  },
  {
    "name" = "mail"
    "type" = "recorddata"
    "value" = "qwertyuiop"
  },
  {
    "name" = "mail"
    "type" = "recordtype"
    "value" = "TXT"
  },
  {
    "name" = "www"
    "type" = "recorddata"
    "value" = "152.152.152.152"
  },
  {
    "name" = "www"
    "type" = "recordtype"
    "value" = "A"
  },
]

I feel that’s not what you were aiming for?

Terraform is already explaining what you must do in the error message:

how did you print out the local.nestedlist structure

Turns out I did not need to use the flatten function at all. This is what worked.

variable "dns_records" {
    www = {
      recordtype = "A"
      recorddata = "152.152.152.152"
    }
    ftp = {
      recordtype = "CNAME"
      recorddata = "www.ftp.org"
    }
}


resource "cloudflare_record" "dns_record" {
  for_each = var.dns_records
  name     = each.key
  type     = each.value["recordtype"]
  value    = each.value["recorddata"]
  zone_id  = "asdfghjklzxcvbnm"
}