How to Create a Subnet in Terraform: Simple Guide
To create a subnet in Terraform, use the
resource "aws_subnet" block specifying the vpc_id, cidr_block, and availability_zone. This defines a subnet within a VPC with the desired IP range and location.Syntax
The aws_subnet resource creates a subnet in AWS. Key parts include:
- vpc_id: The ID of the VPC where the subnet will be created.
- cidr_block: The IP address range for the subnet in CIDR notation.
- availability_zone: The AWS zone where the subnet resides.
terraform
resource "aws_subnet" "example" { vpc_id = "vpc-12345678" cidr_block = "10.0.1.0/24" availability_zone = "us-west-2a" tags = { Name = "example-subnet" } }
Example
This example creates a subnet in an existing VPC with a specific IP range and availability zone. It also tags the subnet for easy identification.
terraform
provider "aws" { region = "us-west-2" } resource "aws_vpc" "example_vpc" { cidr_block = "10.0.0.0/16" tags = { Name = "example-vpc" } } resource "aws_subnet" "example_subnet" { vpc_id = aws_vpc.example_vpc.id cidr_block = "10.0.1.0/24" availability_zone = "us-west-2a" tags = { Name = "example-subnet" } }
Output
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when creating subnets in Terraform include:
- Using an incorrect
vpc_idthat does not exist. - Specifying overlapping
cidr_blockranges with other subnets. - Forgetting to set the
availability_zone, which can cause Terraform to pick a default zone unexpectedly. - Not tagging resources, making management harder.
terraform
/* Wrong: Missing vpc_id */ resource "aws_subnet" "wrong" { cidr_block = "10.0.2.0/24" } /* Right: Include vpc_id and other required fields */ resource "aws_subnet" "right" { vpc_id = "vpc-12345678" cidr_block = "10.0.2.0/24" availability_zone = "us-west-2b" tags = { Name = "correct-subnet" } }
Quick Reference
| Property | Description | Required |
|---|---|---|
| vpc_id | ID of the VPC to create the subnet in | Yes |
| cidr_block | IP range for the subnet in CIDR notation | Yes |
| availability_zone | AWS zone for the subnet | Recommended |
| tags | Key-value pairs to label the subnet | No |
Key Takeaways
Always specify the correct vpc_id to link the subnet to a VPC.
Use a unique cidr_block that does not overlap with other subnets.
Set availability_zone to control subnet placement.
Tag your subnet resources for easier management.
Validate your Terraform configuration before applying.