Search code examples
typesterraformsubnetvpc

How can I retrieve the subnets in a given VPC with Terraform?


I was trying to retrieve the subnets in a given VPC, in my case the default VPC, however I keep getting an error:

data "aws_vpc" "default_vpc" {
  default = true
}

data "aws_subnet" "subnets" {
  vpc_id = data.aws_vpc.default_vpc.id
}

output "subnets_out" {
  value = data.aws_subnet.subnets
}

Error: multiple EC2 Subnets matched; use additional constraints to reduce matches to a single EC2 Subnet

The first data call works, I get my default VPC id, however the second one fails.

Originally I had 1 subnet in my default VPC and at that time, the second data call worked too but to my surprise it returned the subnet as a map instead of a map within a set. So I was curious what would happen if there was more than one subnets in my VPC but then the data call failed.

What I find really confusing is that the Terraform documentation says:

This resource can be useful for getting back a set of subnet IDs.

If it's supposed to return a set of subnet IDs, then why is it an issue that multiple subnets were matched?


Solution

  • aws_subnet is a resource for a specific subnet. Its not for a collection of subnets. so when you pass the VPC_ID, aws is finding more than one subnet in that VPC. Its not possible to store more than one subnets in aws_subnet

    https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/subnet

    aws_subnet provides details about a specific VPC subnet.

    It sounds like you should be using aws_subnets https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/subnets

    This resource can be useful for getting back a set of subnet IDs.

    This will return you a list of subnet ID's which you can then use in a foreach in aws_subnet to get the specific details of each subnet