Introduction
This article details how to use the HCP Terraform cloud integration to remove resources from a workspace managed by HCP Terraform or Terraform Enterprise.
Use Case
Removing specific resources from a state file is useful in the following scenarios:
- When Terraform performs a partial apply, leaving the state file in a condition where it does not reflect your infrastructure.
- When a resource was manually deleted from the cloud provider and the state file needs to be updated to match.
Prerequisites
- An authenticated Terraform CLI session. You may need to run
terraform loginif your local environment is not authenticated with HCP Terraform or Terraform Enterprise.
Procedure
The terraform state command supports all sub-commands (list, mv, pull, push, rm, show) when using the HCP Terraform cloud integration.
-
Define the backend in your configuration.
For Terraform v1.1.0 and newer, use the
cloudblock for the HCP Terraform cloud integration. This is the recommended approach.terraform { cloud { hostname = "my-tfe-hostname" ## Optional for HCP Terraform organization = "my-org" workspaces { name = "my-workspace" } } }For older versions of Terraform (before v1.1.0) or Terraform Enterprise (before v202201-1), you must use the legacy
remotebackend.terraform { backend "remote" { hostname = "my-tfe-hostname" ## Use app.terraform.io for HCP Terraform organization = "my-org" workspaces { name = "my-workspace" } } } -
Initialize Terraform.
Run
terraform initto initialize the backend.$ terraform init
-
List the resources in the state file.
Run
terraform state listto view all resources managed by the state file.$ terraform state list null_resource.testing
-
Remove the target resource.
Run
terraform state rm RESOURCE.ADDRESSto remove the desired resource from the state file.$ terraform state rm null_resource.testing Removed null_resource.testing Successfully removed 1 resource instance(s).
Verification
After removing the resource, navigate to your workspace's States tab in the HCP Terraform or Terraform Enterprise UI to verify that a new state version has been created and no longer includes the resource.