CodexBloom - Programming Q&A Platform

Terraform 1.4.3: working with 'Invalid for_each argument' scenarios When Using Local Variables

👀 Views: 32 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-20
terraform aws security-groups hcl

I'm refactoring my project and I'm working with Terraform 1.4.3 to manage my AWS infrastructure and have run into an scenario with using local variables in a `for_each` argument. I have defined a local variable that is supposed to hold a map of subnets, and I'm trying to create a security group rule for each subnet in that map. However, I'm getting the behavior `behavior: Invalid for_each argument` when I apply my configuration. Here is the relevant part of my code: ```hcl locals { subnet_map = { "subnet-1" = "10.0.1.0/24" "subnet-2" = "10.0.2.0/24" } } resource "aws_security_group" "example" { name = "example_sg" description = "Example security group" dynamic "ingress" { for_each = local.subnet_map content { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = [each.value] description = "Allow HTTP traffic from ${each.key}" } } } ``` I've double-checked that my `local.subnet_map` is defined correctly and that the `for_each` is targeting a valid map. I tried using the `values` function as well, like this:`for_each = values(local.subnet_map)`, but that led to different issues with referencing the keys. What am I missing here? Is it possible to use a local variable with `for_each` in this context? Any help would be greatly appreciated! My team is using Hcl for this CLI tool. Am I approaching this the right way? I'd love to hear your thoughts on this.