How to Use data aws_vpc in Terraform for VPC Lookup
Use the
data "aws_vpc" block in Terraform to look up an existing AWS VPC by specifying its id or filter criteria like tags. This lets you reference VPC attributes in your Terraform configuration without creating a new VPC.Syntax
The data "aws_vpc" block fetches information about an existing AWS VPC. You can specify either the id of the VPC or use filter blocks to find it by tags or other attributes.
- id: The unique identifier of the VPC (e.g.,
vpc-123abc). - filter: One or more filters to find the VPC by attributes like
tag:Name. - most_recent: Optional boolean to select the most recent VPC if multiple match filters.
terraform
data "aws_vpc" "example" { id = "vpc-123abc" } # Or using filter data "aws_vpc" "example" { filter { name = "tag:Name" values = ["my-vpc"] } most_recent = true }
Example
This example shows how to look up an existing VPC by its tag Name and then use its ID to create a subnet inside it.
terraform
provider "aws" { region = "us-east-1" } data "aws_vpc" "selected" { filter { name = "tag:Name" values = ["my-vpc"] } most_recent = true } resource "aws_subnet" "example" { vpc_id = data.aws_vpc.selected.id cidr_block = "10.0.1.0/24" availability_zone = "us-east-1a" }
Output
Terraform will read the existing VPC with tag Name=my-vpc and create a subnet in that VPC with CIDR 10.0.1.0/24 in us-east-1a.
Common Pitfalls
- Not specifying
most_recent = truewhen multiple VPCs match filters can cause errors. - Using
idandfiltertogether is not allowed; choose one. - Forgetting to set the correct AWS region in the provider can cause lookup failures.
- Assuming the data source creates resources; it only reads existing ones.
terraform
data "aws_vpc" "wrong" { id = "vpc-123abc" filter { name = "tag:Name" values = ["my-vpc"] } } # Correct usage: data "aws_vpc" "correct" { filter { name = "tag:Name" values = ["my-vpc"] } most_recent = true }
Quick Reference
Remember these key points when using data aws_vpc:
- Use
idto specify a VPC directly. - Use
filterto find a VPC by tags or attributes. - Set
most_recent = trueif filters match multiple VPCs. - Access attributes like
data.aws_vpc.example.idordata.aws_vpc.example.cidr_block.
Key Takeaways
Use data aws_vpc to read existing VPC info without creating new resources.
Specify either id or filter, never both, to identify the VPC.
Set most_recent = true when filters match multiple VPCs to avoid errors.
Access VPC attributes via data source references for use in other resources.
Ensure your AWS provider region matches the VPC location for successful lookup.