Problem
When running terraform init for a Terraform Enterprise or HCP Terraform workspace using the remotebackend or cloudconfiguration, you receive a 401 Unauthorized error.
│ Error: Error accessing remote module registry
│
│ on main.tf line 39:
│ 39: module "example" {
│
│ Failed to retrieve available versions for module "example"
│ (main.tf:39) from app.terraform.io:
│ error looking up module versions: 401 Unauthorized.Prerequisites
- You are using a local, CLI-driven Terraform execution workflow.
- The module referenced in your configuration is located in a Private Module Registry.
Cause
This error occurs because Terraform does not have a valid API token to authenticate to the Private Module Registry. The CLI requires credentials stored locally, either from running terraform login or from a credentials block in the CLI configuration file.
Supplying a token argument directly within the cloud or remote configuration block is not sufficient for authenticating to the Private Module Registry.
Solution
To resolve this issue, you must provide a valid API token by authenticating the Terraform CLI to Terraform Enterprise or HCP Terraform. You can do this in one of two ways:
-
Use the
terraform logincommand. This is the recommended method, as it securely stores the token for you.$ terraform login
- Manually create a CLI configuration file. You can create a CLI configuration file with credentials that contains a valid token.
After authenticating with either method, run terraform init again. The command should succeed without error.
Additional Information
-
The requirement to authenticate is often displayed in the HCP Terraform or Terraform Enterprise UI, as shown below.
- For more details on credential storage, refer to the documentation on Terraform CLI Credentials.