{"record":{"id":"795fa4864d595c4b","repo":"hashicorp/terraform","slug":"failed-to-create-api-client-s","errorCode":null,"errorMessage":"Failed to create API client: %s","messagePattern":"Failed to create API client: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/command/login.go","lineNumber":657,"sourceCode":"\t\tId:     \"token\",\n\t\tQuery:  fmt.Sprintf(\"Token for %s:\", hostname.ForDisplay()),\n\t\tSecret: true,\n\t})\n\tif err != nil {\n\t\tdiags := diags.Append(fmt.Errorf(\"Failed to retrieve token: %s\", err))\n\t\treturn \"\", diags\n\t}\n\n\ttoken = strings.TrimSpace(token)\n\tcfg := &tfe.Config{\n\t\tAddress:  service.String(),\n\t\tBasePath: service.Path,\n\t\tToken:    token,\n\t\tHeaders:  make(http.Header),\n\t}\n\tclient, err := tfe.NewClient(cfg)\n\tif err != nil {\n\t\tdiags = diags.Append(fmt.Errorf(\"Failed to create API client: %s\", err))\n\t\treturn \"\", diags\n\t}\n\tuser, err := client.Users.ReadCurrent(context.Background())\n\tif err == tfe.ErrUnauthorized {\n\t\tdiags = diags.Append(fmt.Errorf(\"Token is invalid: %s\", err))\n\t\treturn \"\", diags\n\t} else if err != nil {\n\t\tdiags = diags.Append(fmt.Errorf(\"Failed to retrieve user account details: %s\", err))\n\t\treturn \"\", diags\n\t}\n\tc.Ui.Output(fmt.Sprintf(c.Colorize().Color(\"\\nRetrieved token for user [bold]%s[reset]\\n\"), user.Username))\n\n\treturn svcauth.HostCredentialsToken(token), nil\n}\n\nfunc (c *LoginCommand) interactiveContextConsent(hostname svchost.Hostname, grantType disco.OAuthGrantType, credsCtx *loginCredentialsContext) (bool, tfdiags.Diagnostics) {\n\tvar diags tfdiags.Diagnostics\n\tmechanism := \"OAuth\"","sourceCodeStart":639,"sourceCodeEnd":675,"githubUrl":"https://github.com/hashicorp/terraform/blob/d32a084675427f5ac3f7d2868578ef8b2c1dc525/internal/command/login.go#L639-L675","documentation":"Thrown by `terraform login` after `tfe.NewClient(cfg)` returns a non-nil error while constructing an HCP Terraform / Terraform Enterprise (TFE) API client from a user-supplied token. The `tfe.Config` was built from the discovered service address, base path, and the token the user typed at the interactive prompt, but the go-tfe client rejected the configuration as malformed. This is a client-side construction failure, not an HTTP request failure — the token has not yet been sent to any server.","triggerScenarios":"`tfe.NewClient` fails when the `Address`/`BasePath` derived from the host's service discovery document produces an invalid URL (e.g. an empty or non-HTTP(S) address), when the token string is empty after `strings.TrimSpace`, or when go-tfe's internal validation of the config struct rejects it. The error wraps the underlying message with `%s`.","commonSituations":"Logging in to a private TFE instance whose service-discovery `.well-known/terraform.json` returns a malformed `tfe.vN` service endpoint; a misconfigured custom hostname alias that resolves to a non-TFE service; running `terraform login` against a host that does not actually advertise the `tfe.vN` service but the code path reached token entry anyway.","solutions":["Verify the target hostname is a real HCP Terraform or Terraform Enterprise deployment by opening `https://<hostname>/.well-known/terraform.json` in a browser and confirming a `tfe.vN` key with a valid URL.","Re-run `terraform login <hostname>` and ensure the hostname is spelled correctly and reachable from your machine.","If behind a proxy or custom cert, confirm `HTTPS_PROXY` / `SSL_CERT_FILE` are set so service discovery succeeds before token entry.","Inspect the wrapped `%s` detail — it usually names the exact config field go-tfe rejected."],"exampleFix":"// before: hostname with typo\nterraform login app.terraform.io\n// after\nterraform login app.terraform.io  // correct hostname\n// or, for TFE:\nterraform login tfe.corp.example.com","handlingStrategy":"validation","validationCode":"// Validate the hostname and service discovery BEFORE token entry.\n// Run this prior to `terraform login` to confirm the host is real.\ndoc, err := disco.New().Discover(ctx, \"https://\"+hostname)\nif err != nil || doc.TerraformServiceDiscovered() == nil {\n    return fmt.Errorf(\"host %s does not advertise a TFE service; fix discovery before login\", hostname)\n}","typeGuard":"null","tryCatchPattern":"// In Go code wrapping `terraform login` programmatically:\ndiags := loginCmd.Run(args)\nfor _, d := range diags {\n    if strings.Contains(d.Description().Summary, \"Failed to create API client\") {\n        // surface the wrapped %s detail to guide the user to discovery/URL issues\n    }\n}","preventionTips":["Verify service discovery (`.well-known/terraform.json`) for any custom TFE hostname before scripting `terraform login`.","In CI, validate `curl -fsS https://<host>/.well-known/terraform.json` as a pre-check step.","Never feed an empty token; the client will reject it."],"tags":["terraform","login","tfe-client","authentication","config"],"backgroundTag":null,"analyzedSha":"d32a084675427f5ac3f7d2868578ef8b2c1dc525","analyzedAt":"2026-08-11T18:43:52.779Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}