Data Source vs Resource in Terraform: Key Differences and Usage
resource creates or manages infrastructure components, while a data source reads or fetches information from existing infrastructure without changing it. Resources change your cloud environment; data sources only retrieve data for use in your configuration.Quick Comparison
This table summarizes the main differences between resource and data source in Terraform.
| Aspect | Resource | Data Source |
|---|---|---|
| Purpose | Create or manage infrastructure | Read existing infrastructure data |
| Effect on Infrastructure | Modifies or creates resources | No changes made |
| Lifecycle | Has create, update, delete actions | Read-only, no lifecycle actions |
| Use Case | Provision new components | Reference existing components |
| Example | Create an AWS EC2 instance | Get info about an existing AWS VPC |
| State Storage | Stored in Terraform state | Data fetched during plan/apply and stored in state |
Key Differences
Resources in Terraform are the building blocks that define what infrastructure you want to create or manage. When you apply your Terraform configuration, resources are created, updated, or deleted to match your desired state. They have a full lifecycle and their changes are tracked in the Terraform state file.
On the other hand, data sources are used to fetch information about existing infrastructure that Terraform does not manage or that was created outside Terraform. They do not create or modify anything. Instead, they provide data that can be used as input for resources or outputs.
In simple terms, think of resources as the things you build or change, and data sources as the things you look up to get information. For example, you create a virtual machine with a resource, but you get the ID of an existing network with a data source.
Code Comparison
Here is an example of a resource that creates an AWS S3 bucket.
resource "aws_s3_bucket" "example" { bucket = "my-unique-bucket-12345" acl = "private" }
Data Source Equivalent
Here is an example of a data source that reads information about an existing AWS S3 bucket.
data "aws_s3_bucket" "example" { bucket = "my-unique-bucket-12345" } output "bucket_arn" { value = data.aws_s3_bucket.example.arn }
When to Use Which
Choose resource when you want Terraform to create, update, or delete infrastructure components as part of your deployment. Use resource to build new things or manage existing ones fully.
Choose data source when you need to reference or use information about infrastructure that already exists outside Terraform or is managed elsewhere. Use it to read data without making changes.
In short, use resource to build and data source to look up.