0
0
Terraformcloud~5 mins

Terraform state rm for removing resources - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes Terraform's state file has resources that no longer exist or should be managed outside Terraform. The terraform state rm command removes these resources from the state without deleting the actual infrastructure.
When you manually delete a resource outside Terraform and want to update the state to match.
When you want to stop managing a resource with Terraform but keep it running.
When you imported a resource by mistake and want to remove it from state.
When cleaning up state entries for resources that no longer exist.
When splitting infrastructure management between different Terraform projects.
Commands
Initialize the Terraform working directory to download providers and set up the backend.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.50.0... - Installed hashicorp/aws v4.50.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
List all resources currently tracked in the Terraform state to identify the exact resource address to remove.
Terminal
terraform state list
Expected OutputExpected
aws_instance.my_server aws_s3_bucket.my_bucket
Remove the aws_instance.my_server resource from the Terraform state without deleting the actual AWS instance.
Terminal
terraform state rm aws_instance.my_server
Expected OutputExpected
Removed aws_instance.my_server
Verify that the resource aws_instance.my_server is no longer tracked in the Terraform state.
Terminal
terraform state list
Expected OutputExpected
aws_s3_bucket.my_bucket
Key Concept

If you remember nothing else from this pattern, remember: terraform state rm removes resources from Terraform's tracking without deleting the real infrastructure.

Common Mistakes
Running terraform destroy instead of terraform state rm to remove a resource.
terraform destroy deletes the actual resource in the cloud, which may cause unwanted downtime or data loss.
Use terraform state rm to only remove the resource from Terraform's state while keeping it running.
Removing the wrong resource address due to incorrect resource name.
Removing the wrong resource from state can cause Terraform to lose track of important infrastructure.
Always run terraform state list first to confirm the exact resource address before removing.
Summary
Run terraform init to prepare your working directory.
Use terraform state list to see all tracked resources.
Run terraform state rm with the exact resource address to remove it from state without deleting it.
Verify removal by listing state again.