Data Source Block Syntax
What you'll learn: How to structure data blocks in Terraform to query existing infrastructure information.
Understanding Data Source Syntax
While resource blocks create infrastructure, data blocks read information about existing infrastructure or external systems. Think of data sources as read-only queries—they fetch information without making changes.
Basic Data Block Structure
The syntax mirrors resource blocks but uses the data keyword:
data "provider_resourcetype" "name" {
# Query arguments
}
Each data block has three components:
datakeyword – identifies this as a data source- Data source type – combines provider and resource type (e.g.,
aws_ami,azurerm_virtual_network) - Local name – your chosen identifier for referencing this data
Example Data Source
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/ubuntu-*"]
}
}
This queries AWS for an AMI but doesn't create anything.
How Data Sources Differ from Resources
Lifecycle differences:
- Data sources execute during the read phase, before resource creation
- They don't appear in plan output as "create" operations
- Terraform refreshes them on every plan/apply
- You cannot create, update, or destroy them—only query
Configuration differences:
- Data sources have query arguments (filters, identifiers)
- Resources have configuration arguments (size, name, settings)
Referencing Data Source Attributes
Access attributes using data.type.name.attribute:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
}
Key Takeaway: Data blocks use data "type" "name" { } syntax to query existing infrastructure read-only, executing during Terraform's read phase before any resources are created or modified.