Problem
Requests to URLs in the hosted-state-download-url or hosted-json-state-download-url attributes, returned by the State Versions API, result in a 401 unauthorized error.
{
"errors": [
{
"status": "401",
"title": "unauthorized"
}
]
}Prerequisites
- Terraform Enterprise releases
v202311-1or newer.
Cause
Terraform Enterprise v202311-1 introduces a change to the State Versions API to accommodate data retention policies. Previously, the API returned pre-signed URLs in the hosted-state-download-url and hosted-json-state-download-url attributes for direct state downloads.
After this change, the API returns a Terraform Enterprise URL that redirects to a pre-signed URL. HTTP clients must now follow this redirect and provide authentication.
Example of the new URL format in the API response:
{
"hosted-state-download-url": "https://tfe.mycompany.com/api/state-versions/sv-6VyZcPj4cdNRWZxL/hosted_state",
"hosted-json-state-download-url": "https://tfe.mycompany.com/api/state-versions/sv-6VyZcPj4cdNRWZxL/hosted_json_state"
}Solution
HTTP clients that extract URLs from the hosted-state-download-url or hosted-json-state-download-url attributes must be updated to follow redirects and include an Authorization header in the request.
Previous Method (Fails after upgrade)
The following example shows the previous method, where the download URL was fetched and then accessed in a separate, unauthenticated request. This now fails with a 401 error.
## 1. Export the download URL from the API response
$ export HOSTED_STATE_DOWNLOAD_URL=$(curl \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/vnd.api+json" \
https://tfe.mycompany.com/api/v2/workspaces/ws-Kq2fvtVAzF2eFmU4/current-state-version | jq -r '.data.attributes."hosted-state-download-url"')
## 2. Attempt to download the state (this now fails)
$ curl $HOSTED_STATE_DOWNLOAD_URL
## Output
{"errors":[{"status":"401","title":"unauthorized"}]}Corrected Method
To resolve the error, use an HTTP client that can follow redirects and pass the required authentication header. With curl, you can achieve this by adding the -L flag (to follow redirects) and the -H flag (to pass the Authorization header).
$ curl -L -H "Authorization: Bearer $TOKEN" $HOSTED_STATE_DOWNLOAD_URL