Data Source: aws_subnets

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

Example Usage

The following shows outputting all CIDR blocks for every subnet ID in a VPC.

data "aws_subnets" "example" {
  filter {
    name   = "vpc-id"
    values = [var.vpc_id]
  }
}

data "aws_subnet" "example" {
  for_each = toset(data.aws_subnets.example.ids)
  id       = each.value
}

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

The following example retrieves a set of all subnets in a VPC with a custom tag of Tier set to a value of "Private" so that the aws_instance resource can loop through the subnets, putting instances across availability zones.

data "aws_subnets" "private" {
  filter {
    name   = "vpc-id"
    values = [var.vpc_id]
  }

  tags = {
    Tier = "Private"
  }
}

resource "aws_instance" "app" {
  for_each      = toset(data.aws_subnets.private.ids)
  ami           = var.ami
  instance_type = "t2.micro"
  subnet_id     = each.value
}

Argument Reference

More complex filters can be expressed using one or more filter sub-blocks, which take the following arguments:

data "aws_subnets" "selected" {
  filter {
    name   = "tag:Name"
    values = [""] # insert values here
  }
}

Attribute Reference

This data source exports the following attributes in addition to the arguments above:

Timeouts

Configuration options: