Terraform Error: Forecah loop fails with error

Hi Team,

I am trying to fetch the details of VPC which is creating at run time. I have added below data block to fetch the details of the subnet attached to the VPC.

terraform version 0.15.3

**data “aws_subnets” “example” {
filter {
name = “vpc-id”
values = [aws_vpc.vpc.id]
}
}

data “aws_subnet” “example” {
for_each = data.aws_subnets.example.ids
id = each.value
}

output “subnet_cidr_blocks” {
value = [for s in data.aws_subnet.example : s.cidr_block]
}

resource “aws_vpc” “vpc” {
cidr_block = var.cidr_block
instance_tenancy = “default”
enable_dns_hostnames = true
enable_dns_support = true
assign_generated_ipv6_cidr_block = var.enable_ipv6

tags = {
Name = “{var.env}-vpc" Environment = "{var.env}”
}
}**

While running terraform plan I am getting below error:

on modules\network\vpc\vpc.tf line 19, in data “aws_subnet” “example”:
│ 19: for_each = data.aws_subnets.example.ids
│ ├────────────────
│ │ data.aws_subnets.example.ids is a list of string, known only after apply

│ The “for_each” value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how
│ many instances will be created. To work around this, use the -target argument to first apply only the resources that the
│ for_each depends on.

Can you please help me with this error?

Hi @PrateekKhatri,

The error text:

The “for_each” value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created.

Means that the value data.aws_subnets.example.ids is not known until the resources it references are applied, therefor terraform cannot plan how to create individual instances with for_each. While Terraform will always attempt to read a data source during planning when possible, your aws_subnets data source cannot read data about the aws_vpc before the aws_vpc has been created.

Seeing how you are creating the vpc in this configuration, I assume you are also creating the subnets within that vpc and have access to those managed resources as well. I cannot tell what you need the aws_subnet data source for in this example, but in general if you have a managed resource in a configuration you should not be using a data source representing the same logical resource.

If the resources are not in the configuration, you will need some static source of values for the for_each statement. Since at some level the subnets must be created from a static collection of values, that same collection of values would be fed into this configuration to populate the for_each expressions.