HCP Terraform "Required token could not be found" (credentials block) in CI
The cloud {} block (or remote backend) needs an API token to talk to app.terraform.io. In CI there is no interactive terraform login, so unless you set a credentials file or a TF_TOKEN_app_terraform_io variable, the token lookup returns nothing and init fails.
What this error means
terraform init against HCP Terraform fails with "Error: Required token could not be found" and a hint to run terraform login or set the credentials block. It happens only in CI, never on a laptop that already ran login.
Error: Required token could not be found
Run the following command to generate a token for app.terraform.io:
terraform loginCommon causes
No credentials file exists on the runner
On a laptop terraform login writes a token to ~/.terraform.d/credentials.tfrc.json. A fresh CI runner has no such file, so the backend finds no token.
The TF_TOKEN_ variable name does not match the host
The host-scoped variable must be TF_TOKEN_app_terraform_io (dots in the hostname become underscores). A misspelled name is ignored and the token is not seen.
How to fix it
Set the host-scoped token variable
- Create a user or team API token in HCP Terraform.
- Store it as a CI secret.
- Expose it to the step as
TF_TOKEN_app_terraform_ioso the backend reads it without a credentials file.
env:
TF_TOKEN_app_terraform_io: ${{ secrets.TF_API_TOKEN }}Write a credentials file if you prefer
Some setups write the token to the credentials file instead of using the env var. Either works; do not do both with mismatched tokens.
mkdir -p ~/.terraform.d
cat > ~/.terraform.d/credentials.tfrc.json <<EOF
{"credentials":{"app.terraform.io":{"token":"$TF_API_TOKEN"}}}
EOFHow to prevent it
- Inject the token as
TF_TOKEN_app_terraform_ioin every workflow that talks to HCP Terraform. - Use a team token scoped to the workspaces the pipeline needs.
- Never rely on a cached
terraform loginfrom a developer machine.