Introduction
This article details how to use the remote
backend to remove resources within a workspace managed by Terraform Cloud or Terraform Enterprise.
Use Case
Removing specific resources is useful in the following scenarios:
When Terraform performed a partial apply, leaving the state file in a condition where it does not reflect reality.
When the resource was manually deleted from the cloud provider and the state file needs to be updated.
Procedure
The remote backend stores the Terraform state and may be used to run state operations in Terraform Enterprise. terraform state
supports all sub-commands: (list, mv, pull, push, rm, show)
To start the process of removing a resource ensure that the remote backend is in the Terraform configuration.
terraform {
backend "remote" {
hostname = "TFEHOSTNAME.com"
organization = "company"
workspaces {
name = "my-app-prod"
}
}
}
Once the remote
backend is defined in the Terraform configuration, run terraform init
to initialize the backend.
$ terraform init
Initializing the backend...
Successfully configured the backend "remote"! Terraform will automatically
use this backend unless the backend configuration changes.
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
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. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
Once initialized, run terraform state list
to list all resources managed by the state file. Subsequently, terraform state rm $RESOURCE
command to remove the resource.
$ terraform state list
null_resource.testing
$ terraform state rm null_resource.testing
Removed null_resource.testing
Successfully removed 1 resource instance(s).
After the resource has been identified, targeted, and removed, check the workspace’s State tab to verify that a new state has been uploaded.