Home > Blockchain >  Data resource of Network_interface throws invalid count argument Terraform
Data resource of Network_interface throws invalid count argument Terraform

Time:08-31

I am trying to get the network interface ids of a VPC endpoint using the data resource of aws_network_interface, the code for which looks like

resource "aws_vpc_endpoint" "api-gw" {
  vpc_id       = var.vpc_id
  service_name = "com.amazonaws.${var.aws_region}.execute-api"

  vpc_endpoint_type   = "Interface"
  security_group_ids  = [aws_security_group.datashop_sg.id]
  private_dns_enabled = true

  subnet_ids = [data.aws_subnet.private-1.id]
}

data "aws_network_interface" "endpoint-api-gw" {
  count = length(aws_vpc_endpoint.api-gw.network_interface_ids)
  id    = tolist(aws_vpc_endpoint.api-gw.network_interface_ids)[count.index]
}

I get the following error

Error: Invalid count argument
│
│   in data "aws_network_interface" "endpoint-api-gw":
│   count = length(aws_vpc_endpoint.api-gw.network_interface_ids)
│
│ The "count" 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 count depends on.

I have also tried the for_each and it gives similar error of it is dependent on resources. I am running out of ideas. It would be of great if someone can help

CodePudding user response:

The error is clear:

count = length(aws_vpc_endpoint.api-gw.network_interface_ids)

is only known after apply. You can't do this. count value must be known at plan time. You have to run your TF in two stages:

  1. Execute TF with -target to deploy only aws_vpc_endpoint.api-gw using option.
  2. Execute it again, to deploy the rest.

Otherwise, you have to re-factor you code, and fully eliminate the dependency of the count on aws_vpc_endpoint.api-gw.network_interface_ids.

  • Related