How to Create a Resource in Terraform: Simple Guide
To create a resource in
Terraform, define a resource block with a resource type and name, then specify its configuration inside. Running terraform apply will create the resource in your cloud or infrastructure provider.Syntax
A resource block in Terraform has three parts: the keyword resource, the resource type (like aws_instance), and a unique resource name. Inside the block, you add settings that define the resource's properties.
- resource: keyword to declare a resource
- resource type: the kind of resource you want to create (depends on provider)
- resource name: a unique label for this resource in your config
- configuration: key-value pairs that set resource details
terraform
resource "resource_type" "resource_name" { # configuration settings }
Example
This example creates an AWS EC2 instance resource named example. It sets the AMI and instance type. Running terraform apply will launch this virtual machine in AWS.
terraform
provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when creating resources include:
- Using incorrect resource type names or misspelling them.
- Not providing required configuration arguments.
- Forgetting to initialize Terraform with
terraform initbefore applying. - Not setting provider configuration, so Terraform doesn't know where to create the resource.
Always check the provider documentation for required fields.
terraform
/* Wrong: Missing required 'ami' argument */ resource "aws_instance" "bad_example" { instance_type = "t2.micro" } /* Correct: Includes required 'ami' */ resource "aws_instance" "good_example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" }
Quick Reference
| Element | Description |
|---|---|
| resource | Keyword to declare a resource block |
| resource_type | Type of resource from provider (e.g., aws_instance) |
| resource_name | Unique name for the resource in config |
| configuration | Settings inside the block defining resource properties |
| terraform init | Command to initialize Terraform and download providers |
| terraform apply | Command to create or update resources |
Key Takeaways
Define resources using the resource block with type and name.
Always include required configuration arguments for the resource.
Run terraform init before terraform apply to prepare your environment.
Check provider docs to know valid resource types and settings.
Use terraform apply to create or update your infrastructure.