What are Terraform data sources and how do they differ from resources?
A resource creates, updates, or destroys infrastructure. A data source reads existing infrastructure that is managed outside of your current Terraform code — it is read-only.
# Data source — reads an existing VPC by tag, does not create it
data "aws_vpc" "main" {
tags = {
Environment = "production"
}
}
# Use the data source output
resource "aws_subnet" "app" {
vpc_id = data.aws_vpc.main.id
...
}
Data sources are essential for referencing shared infrastructure managed by a different team or Terraform root module.