Introduction
We may need to download state file locally using HCP Terraform API. We have API calls to show a state version or fetch the current state version as mentioned in this article. However, this does not mention a direct way to download the state file from workspace.
In order to download the state file we can use the hosted-state-download-url as illustrated in the procedure below:
Procedure
- Get the state version of the state file that needs to be downloaded through API.
- Go to your HCP Terraform Workspace >> States >> Copy the state version of the state file in the format sv-****************. Refer screenshot below:
- Go to your HCP Terraform Workspace >> States >> Copy the state version of the state file in the format sv-****************. Refer screenshot below:
- export the user token from HCP terraform to be used in the curl command in a variable called TOKEN:
-
export TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-
- Execute the below curl request. Replace your_terraform_state_file_name with the name of the file that you would like to download and update the value of sv-**************** with the state version of the state that you would like to download.
-
curl -L -o your_terraform_state_file_name.tfstate\
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/vnd.api+json" \
https://app.terraform.io/api/state-versions/sv-****************/hosted_state
-
- The state file will be downloaded locally.