Get default AWS network resources using Terraform
Posted: | Tags: cloud aws terraform tilData sources are used to retrieve information outside of Terraform, in this case default VPC, subnets, security group and internet gateway resources provisioned in a region within an AWS account. Each opted-in region within an AWS account comes with default network resources, with can be used to provision resources within a default subnet, use the default internet gateway or security group for provisoned resources and more.
Retrieve the default VPC
The default VPC can be retrieved using the aws_vpc
data source and the default argument. We will use the default VPC ID to retrieve all other default network resources.
data "aws_vpc" "default_vpc" {
default = true
}
Retrieve default subnets
Using the aws_subnet
data source and filtering by the default VPC ID we can get all the default subnets in a list.
data "aws_subnets" "default_subnets" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default_vpc.id]
}
}
Retrieve the default security groups
With the default VPC ID we can use the aws_security_group
data source and the vpc_id
and name
argument to get the default security group.
data "aws_security_group" "default_security_group" {
vpc_id = data.aws_vpc.default_vpc.id
name = "default"
}
Retrieve the default internet gateway
Filtering the aws_internet_gateway
data source by the VPC ID we can get the default internet gateway.
data "aws_internet_gateway" "default_internet_gateway" {
filter {
name = "attachment.vpc-id"
values = [data.aws_vpc.default_vpc.id]
}
}
Full code
Putting everything together with the provider and ouput, running the following code with terraform plan
will give you a preview of all the resource IDs.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "eu-central-1"
}
data "aws_vpc" "default_vpc" {
default = true
}
data "aws_subnets" "default_subnets" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default_vpc.id]
}
}
data "aws_security_group" "default_security_group" {
vpc_id = data.aws_vpc.default_vpc.id
name = "default"
}
data "aws_internet_gateway" "default_internet_gateway" {
filter {
name = "attachment.vpc-id"
values = [data.aws_vpc.default_vpc.id]
}
}
output "default_vpc_id" {
value = data.aws_vpc.default_vpc.id
}
output "default_subnet_ids" {
value = data.aws_subnets.default_subnets.ids
}
output "default_security_group_id" {
value = data.aws_security_group.default_security_group.id
}
output "default_internet_gatway_id" {
value = data.aws_internet_gateway.default_internet_gateway.id
}