Course contentsShow
← Cloud and Infrastructure
Lesson 753 of 2,98914. Terraform FundamentalsFree lesson

When to Use Resources vs Data Sources

Decide between managing infrastructure with resources or querying existing infrastructure with data sources.

When to Use Resources vs Data Sources

What you'll learn: How to decide whether to create and manage infrastructure with resources or query existing infrastructure with data sources.

The Core Distinction

Think of Terraform resources as building blocks you own and control—like constructing a new house. Data sources, on the other hand, are like looking up information in a directory—you're referencing something that already exists but you didn't create it (or don't want to manage it in this particular configuration).

Use Resources When You Want To:

  • Create new infrastructure from scratch (compute instances, networks, databases)
  • Own the lifecycle of that infrastructure—Terraform will create, update, and destroy it
  • Manage configuration changes over time through your code
  • Track state and ensure your declared configuration matches reality

Example scenario: You're deploying a new application and need to provision EC2 instances, load balancers, and security groups. These are all resources because you're creating and managing them.

Use Data Sources When You Want To:

  • Query existing infrastructure that's managed elsewhere or already exists
  • Reference values from infrastructure you don't control in this configuration
  • Fetch dynamic information like AMI IDs, availability zones, or DNS records
  • Keep your configuration read-only for certain infrastructure components

Example scenario: You need to deploy into an existing VPC that another team manages, or you want to use the latest Amazon Linux AMI without hardcoding its ID. Use data sources to look these up.

The Practical Rule

Ask yourself: "Am I creating this, or am I just looking it up?" If creating and managing—use a resource. If referencing something that exists independently—use a data source.

Key Takeaway: Use resources to create and manage infrastructure you own; use data sources to query and reference existing infrastructure you only need to read from.