Skip to main content
In Terraform, understanding the difference between resources and data sources is essential for predictable infrastructure as code. While they can look similar in HCL syntax, their roles, lifecycle behaviors, and impacts on state differ. This guide compares both, shows examples, and gives guidance on when to use each. Why this matters: resources are objects Terraform creates and manages (tracked in state), whereas data sources are read-only lookups that retrieve information about infrastructure that Terraform does not own.

Key differences at a glance

The image is a comparison table between "Resource" and "Data Source" in Terraform, detailing differences in keywords, functionality, infrastructure management, lifecycle involvement, and alternate names.
Data sources only provide information about existing infrastructure; they do not modify or take ownership of it. Resources, by contrast, are owned and managed by Terraform.
Use resources when Terraform should own the lifecycle of an object. Use data sources when you only need to look up existing information (for example, a VNet ID or an AMI ID).

Examples (syntactic comparison)

resource example — Terraform will create and manage this virtual network:
data source example — Terraform will look up an existing virtual network but will not manage it:

When to use each

  • Use resource when:
    • Terraform should create, update, or delete the object.
    • You want the object tracked in Terraform state.
    • You need full lifecycle management and drift detection.
  • Use data when:
    • The object is managed outside this Terraform configuration (or by another team).
    • You need to reference attributes (IDs, names, subnet lists, AMI IDs).
    • You want to avoid Terraform creating duplicate or conflicting infrastructure.

Practical tips

  • Prefer data sources for shared resources (e.g., centrally managed networks, shared subnets).
  • Avoid using data sources as a workaround to hide unmanaged drift — if you need to manage something consistently, convert it into a resource.
  • Remember that data lookups may introduce dependency ordering; reference them explicitly to ensure correct evaluation.

References

Summary: resources manage lifecycle and are tracked in state; data sources read and expose attributes from existing infrastructure without taking ownership.

Watch Video