Read Existing Infrastructure with Terraform Data Sources
Data sources let you reference infrastructure that exists outside your Terraform configuration without importing it.
What
Data sources let Terraform read information about infrastructure that exists outside your current configuration. They query the cloud provider API and return attributes you can reference in your resources. Use them to look up AMI IDs, VPCs managed by another team, availability zones, or any existing resource.
Why It Matters
Not everything in your cloud account is managed by a single Terraform configuration. Other teams may manage shared VPCs, IAM roles, or DNS zones. Data sources let you reference these resources safely without taking ownership of them or risking accidental modification.
Example
# Look up the latest Ubuntu AMI
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
# Look up an existing VPC by tag
data "aws_vpc" "shared" {
filter {
name = "tag:Name"
values = ["shared-vpc"]
}
}
# Use data source attributes in resources
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
subnet_id = data.aws_vpc.shared.id
}
# Reference with data.<type>.<name>.<attribute>Common Mistake
Using data sources to read resources that are managed in the same Terraform configuration. If you already have a resource block for it, reference the resource directly instead of creating a redundant data source lookup.
Quick Fix
Use resource references (aws_vpc.main.id) for resources in your config, and data sources (data.aws_vpc.shared.id) only for resources managed elsewhere. This keeps your dependency graph clean and avoids unnecessary API calls.
Key Takeaways
- 1Data sources READ existing infrastructure without managing it
- 2Use filters to find resources by tags, names, or attributes
- 3Reference with data.<type>.<name>.<attribute>
- 4Only use data sources for resources outside your config
- 5Great for shared VPCs, AMI lookups, and cross-team resources
Was this tip helpful?
Help us improve the DevOpsPath daily collection