How to Use terraform state rm to Remove Resources from State
Use
terraform state rm <resource_address> to remove a resource from Terraform's state file without deleting the actual resource. This is useful when you want Terraform to stop managing a resource but keep it running.Syntax
The terraform state rm command removes a resource from the Terraform state file. It takes the resource address as an argument, which identifies the resource in the state.
terraform state rm <resource_address>: Removes the specified resource from the state.
The resource address usually looks like module.module_name.resource_type.resource_name or simply resource_type.resource_name.
bash
terraform state rm <resource_address>
Example
This example shows how to remove an AWS S3 bucket resource named aws_s3_bucket.my_bucket from the Terraform state. The bucket will remain in AWS but Terraform will no longer manage it.
bash
terraform state rm aws_s3_bucket.my_bucket
Output
Removed aws_s3_bucket.my_bucket
Common Pitfalls
- Removing the wrong resource: Double-check the resource address before running the command to avoid losing track of managed resources.
- Expecting resource deletion:
terraform state rmdoes not delete the actual resource, only removes it from state. - State file corruption: Avoid manual edits to the state file; use Terraform commands to modify state safely.
bash
## Wrong: Trying to delete resource with state rm terraform state rm aws_s3_bucket.my_bucket ## Right: Use terraform destroy to delete resource terraform destroy -target=aws_s3_bucket.my_bucket
Quick Reference
Use this quick guide to remember key points about terraform state rm:
| Command | Description |
|---|---|
| terraform state rm | Remove resource from Terraform state only |
| terraform destroy -target= | Delete resource from infrastructure and state |
| terraform state list | List all resources in the current state |
| terraform state show | Show details of a resource in state |
Key Takeaways
Use terraform state rm to remove a resource from state without deleting it.
Always verify the resource address before removing it from state.
terraform state rm does not affect the actual infrastructure.
Use terraform destroy to delete resources from both state and infrastructure.
Avoid manual edits to the state file; use Terraform commands instead.