Terraform Tutorial — What Are Data Sources?
Data sources are Terraform’s way of fetching information about resources that already exist — whether they were created by Terraform, by hand, or by another tool.
Resource vs Data Source
| Aspect | resource | data |
|---|---|---|
| Keyword | resource |
data |
| Operation | Create, update, destroy | Read only |
| In state? | Yes — full lifecycle | Yes — as a reference |
| Changes infra? | Yes | No |
# Resource: Terraform manages this VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
# Data source: Terraform reads this VPC (created elsewhere)
data "aws_vpc" "existing" {
id = "vpc-0abc123def456"
}
When to Use Data Sources
| Scenario | Example |
|---|---|
| Look up an AMI ID | Find the latest Amazon Linux 2023 AMI |
| Reference an existing VPC | Deploy into a VPC created by another team |
| Get availability zones | Dynamically get AZs for the current region |
| Read an IAM policy | Reference a managed AWS policy by name |
| Look up a Route53 zone | Get the zone ID for DNS record creation |
Data Source Syntax
data "PROVIDER_TYPE" "LOCAL_NAME" {
# Arguments to filter/identify the resource
}
Access attributes with data.PROVIDER_TYPE.LOCAL_NAME.attribute:
data "aws_vpc" "main" {
id = "vpc-0abc123"
}
resource "aws_subnet" "web" {
vpc_id = data.aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
Data Sources Are Refreshed Every Plan
Every time you run terraform plan or terraform apply, Terraform queries the API to get the latest data. This means data source values are always current.
What’s Next?
Let’s dive deeper into the data block syntax and its attributes.