Problem
When a workspace is deleted from HCP Terraform or Terraform Enterprise, the workspace and its state are removed. This action cannot be undone through the UI. If the infrastructure managed by that workspace still exists, you must recreate the workspace and re-associate it with the existing resources to avoid drift and ensure proper management.
Procedure
The first step in either recovery scenario is to create a new workspace with the same name and configuration as the one that was deleted. This includes connecting it to the same version control system (VCS) repository and setting the same execution mode and variable sets.
Next, update your Terraform configuration to use the new workspace by defining the remote backend. This configuration tells the Terraform CLI to use your new HCP Terraform or Terraform Enterprise workspace for state storage and operations.
Update your configuration with the following terraform block, replacing the hostname, organization, and workspaces.name values with your specific details.
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "your-organization"
workspaces {
name = "your-workspace-name"
}
}
}After configuring the backend, run terraform init to connect to the new workspace. Once initialized, choose one of the following solutions based on whether you have a backup of the original state file.
Solutions
Solution 1: Recovering with a State File Backup
If you have a backup of the deleted workspace's state file, you can restore it to the new workspace. This is the most direct method for recovery.
Use the terraform state push command to upload your backup state file to the newly created workspace. You can provide the path to your state file or use - to pipe the file content from standard input.
$ terraform state push /path/to/your/terraform.tfstate
After pushing the state, run terraform plan to confirm that Terraform correctly recognizes the existing infrastructure and that no changes are planned.
Solution 2: Recovering without a State File Backup
If you do not have a backup of the state file, you must manually import each existing resource into the new workspace's state.
Use the terraform import command for each resource defined in your configuration. You need to provide the resource address from your configuration and the resource's ID from your cloud provider.
The following example demonstrates importing a Docker container.
$ terraform import docker_container.web $(docker inspect --format="{{.ID}}" hashicorp-learn)Repeat this process for all resources managed by the workspace. After importing all resources, run terraform plan to verify that the new state file matches your existing infrastructure and that no changes are necessary.