Data Source Patterns and Dependencies
What you'll learn: How to use advanced data source techniques to filter information and manage dependencies between data sources and resources.
The Core Idea
Data sources become powerful when you master chaining them together and filtering their results. Just like a detective gathering clues in sequence—where finding one piece of information leads to discovering the next—you can create data sources that depend on other data sources or resources, and filter those results to get exactly what you need.
Dependency Patterns
Terraform automatically handles dependencies when you reference attributes from one data source in another:
data "aws_vpc" "main" {
filter {
name = "tag:Environment"
values = ["production"]
}
}
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [data.aws_vpc.main.id] # Depends on vpc data source
}
}
The aws_subnets data source waits for the VPC data source to complete first, creating an implicit dependency chain.
Filtering Patterns
Most cloud provider data sources support filtering to narrow results:
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
This pattern ensures you're querying the exact resource you need, avoiding ambiguity or stale data.
Combining with Resources
Data sources can depend on resources you've just created, enabling dynamic lookups:
resource "aws_instance" "app" {
ami = data.aws_ami.ubuntu.id
subnet_id = data.aws_subnets.private.ids[0]
instance_type = "t2.micro"
}
Key Takeaway: Master data source dependencies by chaining references and using filters to query exactly what you need—this creates robust, dynamic infrastructure configurations that adapt to existing cloud environments.