Data sources
A data source reads information from existing infrastructure or external systems. Unlike a resource, Terraform does not create, update, or delete anything — it only fetches data for use elsewhere in your configuration.
flowchart LR
resource["resource block"] -- "creates, updates,<br/>deletes" --> managed["Object managed<br/>by Terraform"]
data["data block"] -- "reads only" --> existing["Existing object managed<br/>elsewhere"]
Declare a data source using a data block:
| |
A data source has a type (local_file) and a local name (settings), just like a resource. The arguments inside the block tell the provider what to look up.
Reference the fetched data using the data.<TYPE>.<NAME>.<attribute> syntax:
| |
A common real-world use case is looking up infrastructure managed outside of your configuration, e.g. the latest machine image for a virtual machine:
| |
Terraform reads data sources during terraform plan, so the fetched values are always up to date when Terraform calculates what to change.
Best practices
- Use data sources instead of hardcoding IDs and other values that already exist in your infrastructure.
- Make lookup arguments specific enough to match exactly one object — ambiguous queries cause errors or, worse, the wrong object being used.
- If your configuration both creates an object and reads it back, use a resource reference instead of a data source.