Problem: You have resources already created in AWS (manually or by another project). You need to use them in Terraform but don't want to recreate them.
Solution: Data sources let you fetch existing resources instead of creating new ones.
resource "aws_vpc" ... → creates a new VPC
data "aws_vpc" ... → fetches an existing VPC
# Define
data "resource_type" "label" {
# filters to find the right resource
}
# Use
data.resource_type.label.attribute
resource |
data |
|
|---|---|---|
| Purpose | Create new | Fetch existing |
| Syntax | resource "aws_vpc" "name" |
data "aws_vpc" "name" |
| Access | aws_vpc.name.id |
data.aws_vpc.name.id |
| Stored in state? | Yes | No (read only) |
Problem: AMI IDs are different per region and change over time. Hardcoding them breaks things.
Solution: Fetch the latest AMI automatically.
data "aws_ami" "latest" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
# Use in EC2 — always gets the correct latest AMI
resource "aws_instance" "myserver" {
ami = data.aws_ami.latest.id
instance_type = "t3.micro"
}
Problem: VPC was created manually or by another project. You need its ID.
Solution: Fetch it by tag name.