Problem
When you run the terraform login command to authenticate with HCP Terraform or Terraform Enterprise, you receive an error after providing your API token.
$ terraform login your-tfe-hostname.com Terraform will request an API token for your-tfe-hostname.com. If login is successful, Terraform will store the token in plain text in the following file for use by subsequent commands: ... Enter a token: Error: Token is invalid: unauthorized
Cause
There are two primary causes for this error.
- SAML Session Timeout: When using SAML for authentication, HCP Terraform and Terraform Enterprise associate the API token with the SAML session's lifetime. If the session expires, the token becomes invalid.
- Hidden Characters in Token: When you copy the token from a web browser or another application, it may include invisible formatting or whitespace. This causes the CLI to process an invalid string, leading to an authorization failure.
Solutions
Solution 1: Refresh the SAML Session
If your organization uses SAML authentication, your session may have expired. Refreshing the session and generating a new token typically resolves the issue.
- Sign out of your HCP Terraform or Terraform Enterprise account in your web browser.
- Sign back in to establish a new SAML session.
- Generate a new API token from the user settings.
- Run
terraform loginagain and use the new token.
Solution 2: Sanitize the API Token
To ensure you are not pasting hidden characters into the terminal, first paste the token into a plain text editor.
- Copy the API token from the HCP Terraform or Terraform Enterprise UI.
- Paste the token into a plain text editor (such as Notepad, TextEdit in plain text mode, or VS Code).
- Copy the token from the text editor.
- Run
terraform loginand paste the sanitized token into the prompt.
Additional Information
For more details on the command, refer to the official terraform login documentation.