Referencing Data Source Attributes
What you'll learn: How to use the outputs from data sources in your Terraform resource configurations.
Once you've defined a data source in Terraform, you need to access its retrieved information to use it elsewhere in your infrastructure code. This is where the data reference syntax comes in.
The Core Syntax
To reference any attribute from a data source, use this pattern:
data.<resource_type>.<name>.<attribute>
- data — The prefix indicating you're referencing a data source (not a managed resource)
- resource_type — The type of data source (e.g.,
aws_ami,azurerm_resource_group) - name — The local name you gave the data source in your configuration
- attribute — The specific output field you want to access
Practical Example
If you've queried an existing VPC like this:
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["production-vpc"]
}
}
You can reference its ID in a subnet resource:
resource "aws_subnet" "app" {
vpc_id = data.aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
Here, data.aws_vpc.main.id retrieves the id attribute from your data source.
Think of It Like This
Data sources are like reference books—you look up information, then cite it. The data. prefix is your citation format, telling Terraform "this value comes from something I looked up, not something I'm creating."
Key Takeaway: Access data source outputs using data.<resource_type>.<name>.<attribute> syntax to inject existing infrastructure details into your new resource configurations.