Reference to "each" in context without for_each

Hello, i am migrating the code from classic waf to wafv2, in one of my data modules I am using the for each loop to retrieve the list of IP addresses and block those IP’s by using the waf_acl rule.
when i am run the terraform plan getting the below error:

Error: Reference to "each" in context without for_each
│
│   on global-main.tf line 52, in resource "aws_wafv2_web_acl" "dev":
│   52:         arn = data.aws_wafv2_ip_set.whitelists[each.key].arn
│
│ The "each" object can be used only in "module" or "resource" blocks, and only when the "for_each" argument is set.

Below is my sample code:

data "aws_wafv2_ip_set" "whitelists" {
  for_each = { for v in var.whitelist_ip_sets : v => v }
  name = each.value
  scope = "CLOUDFRONT"
}
resource "aws_wafv2_web_acl" "test" {
  name        = "testWebAcl-${var.environment}"
  scope = "CLOUDFRONT"

  default_action {
    allow {}
  }

  rule {
    name        = "ADN whitelist"
    priority = 10

    action {
      block {}
    }

    statement {
      ip_set_reference_statement {
        arn = data.aws_wafv2_ip_set.whitelists[each.key].arn
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = false
      metric_name                = "testWebAcl${var.environment}"
      sampled_requests_enabled   = false
      }
    }
}

So, please suggest if any mistake in my code.
Thanks in advance.

Hi @sadik13

Your aws_wafv2_web_acl resource is using each.key in the statement block, but that resource is not using for_each, so there is no each value to reference there.