Introduction to the problem
There isn't a predefined solution for backup purposes. The Terraform Cloud state file is stored in an AWS S3 bucket. In certain cases, the state files could be lost. Let's say because of human error a workspace was deleted and now the state cannot be recovered. To avoid such a problem, copies of the state files can be stored in a different location.
How to backup the state file using the Terraform Cloud API
The solution for the state backups should be picked by the user by weighing in on the pros and cons. Here is a proposed way of how to go about this.
The Terraform Cloud API can be used to list all the workspaces in an organization.
curl \
--header"Authorization: Bearer $TOKEN" \
--header"Content-Type: application/vnd.api+json" \
https://app.terraform.io/api/v2/organizations/<ORG_NAME>/workspaces | jq -r '.data [].id'
After you get the list of workspace IDs, you can use the following endpoint to get the download link for the current state version.
curl \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/vnd.api+json" \
https://app.terraform.io/api/v2/workspaces/<WORKSPACE_ID>/current-state-version | jq -r '.data.attributes."hosted-state-download-url"'
Having the URL of the state, the user can then initiate a new curl command to save the state file locally.
curl -L -o terraform.tfstate \
--header "Authorization: Bearer $TOKEN" \
https://app.terraform.io/api/state-versions/<STATE_VERSION_ID>/hosted_state
Additional Information
If you have any questions or you need help please contact support at tf-cloud@hashicorp.support or submit a ticket via our support portal.