What Is Resource in Terraform: Definition and Usage
resource is a block that defines a piece of infrastructure, like a server or database, that Terraform manages. It describes what you want to create, update, or delete in your cloud or service provider.How It Works
Think of a resource in Terraform as a recipe for creating something in the cloud, like a virtual machine or a storage bucket. You write down the details of what you want, and Terraform follows this recipe to build or change that infrastructure.
Terraform keeps track of all these resources in a state file, like a checklist, so it knows what exists and what needs to be updated or removed. When you run Terraform commands, it compares your recipe to the current state and makes only the necessary changes.
Example
This example shows a Terraform resource that creates a simple AWS S3 bucket. It tells Terraform to make a storage bucket named "my-unique-bucket-12345".
resource "aws_s3_bucket" "my_bucket" { bucket = "my-unique-bucket-12345" acl = "private" }
When to Use
Use resource blocks whenever you want Terraform to create or manage something in your cloud or service provider. This includes servers, databases, networks, storage, and many other infrastructure parts.
For example, if you want to launch a virtual machine, set up a database, or create a DNS record, you write a resource block describing it. Terraform then ensures these resources exist and match your description.
Key Points
- A
resourcedefines infrastructure components Terraform manages. - Resources describe what you want, not how to do it.
- Terraform tracks resources in a state file to manage changes safely.
- Resources cover many cloud services like servers, storage, and networking.