Get VPC information and subnets
Posted on 26-Mar-2022
Get Default VPC and Public Subnets
data "aws_vpc" "default" {
default = true
}
data "aws_subnets" "all" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
output "first_subnet_id" {
value = sort(data.aws_subnets.all.ids)[0]
}
Get custom VPC with Public/Private subnets
locals {
vpc_name = "myvpc"
}
data "aws_vpc" "vpc" {
filter {
name = "tag:Name"
values = [local.vpc_name]
}
}
data "aws_subnets" "public" {
filter {
name = "vpc-id"
values = [data.aws_vpc.vpc.id]
}
filter {
name = "tag:Name"
values = ["${local.vpc_name}-public-*"]
}
}
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [data.aws_vpc.vpc.id]
}
filter {
name = "tag:Name"
values = ["${local.vpc_name}-private-*"]
}
}