Data Sources and Dependencies (read existing infrastructure)
Learn how Terraform data sources fetch information from providers, and how Terraform resolves dependencies between resources.
Terraform can manage infrastructure (resources) or read existing infrastructure (data sources).
Terraform also builds a dependency graph to decide what to create first.
Learning outcomes
You’ll learn:
- the difference between resources and data sources
- how to use data sources to query existing objects
- how dependencies are inferred (and when you must set
depends_on)
1) Resources vs data sources
Resource
Terraform creates/updates/destroys the object.
resource "aws_vpc" "main" {
# Terraform manages the VPC lifecycle
}
Data source
Terraform reads data only.
data "aws_vpc" "existing" {
# Terraform only queries
}
2) Example: reading an existing VPC
This example is AWS-flavored, but the concept applies to all providers.
data "aws_vpc" "selected" {
filter {
name = "tag:Name"
values = ["production-vpc"]
}
}
Then you use data.aws_vpc.selected.id in other resources.
Example (conceptual):
resource "aws_security_group" "sg" {
name = "web-sg"
vpc_id = data.aws_vpc.selected.id
}
3) Dependency graph (how Terraform orders operations)
Terraform typically infers dependencies from references.
Example:
resource "aws_instance" "web" {
ami = "ami-..."
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web_sg.id]
}
Terraform knows:
- it needs
aws_security_group.web_sgbeforeaws_instance.web
4) When inference is not enough: depends_on
Sometimes dependencies aren’t detectable because you didn’t reference attributes directly.
Use depends_on to force ordering.
resource "aws_s3_bucket" "bucket" {
bucket = "my-unique-name-12345"
}
resource "aws_s3_bucket_notification" "notify" {
bucket = aws_s3_bucket.bucket.id
# ... notification configuration that Terraform can't fully infer ...
depends_on = [aws_s3_bucket.bucket]
}
5) Data sources and plan-time behavior
Data sources are evaluated during planning (and sometimes during apply).
If your data source depends on resources created in the same plan, you must structure references so Terraform can order correctly.
Rule of thumb:
- prefer referencing resource attributes instead of hardcoding IDs
- ensure any “query existing object” is stable and available at plan time
6) Cleanup reminder
Data sources don’t create resources, so there’s nothing to destroy for them.