【问题标题】:GCP App Engine - Could not load the default credentialsGCP App Engine - 无法加载默认凭据
【发布时间】:2021-01-06 20:53:01
【问题描述】:

我正在开发一个使用 GCP 和 App Engine 的项目。在开发中,它会打印出错误信息:

2020-09-20 15:07:24 dev[development]  Error: Could not load the default credentials. Browse 
to https://cloud.google.com/docs/authentication/getting-started for more information.      
at GoogleAuth.getApplicationDefaultAsync (/workspace/node_modules/google-auth-
library/build/src/auth/googleauth.js:161:19)      at runMicrotasks (<anonymous>)      at 
processTicksAndRejections (internal/process/task_queues.js:97:5)      at runNextTicks 
(internal/process/task_queues.js:66:3)      at listOnTimeout (internal/timers.js:518:9)      
at processTimers (internal/timers.js:492:7)      at async GoogleAuth.getClient 
(/workspace/node_modules/google-auth-library/build/src/auth/googleauth.js:503:17)      at 
async GrpcClient._getCredentials (/workspace/node_modules/google-
gax/build/src/grpc.js:108:24)      at async GrpcClient.createStub 
(/workspace/node_modules/google-gax/build/src/grpc.js:229:23)

请记住,这是开发模式,但在 GCP App Engine 基础架构上运行,而不是在 localhost 上运行。我正在使用以下命令查看日志:

gcloud app logs tail -s dev

根据 GCP App Engine 文档@https://cloud.google.com/docs/authentication/production#cloud-console

If your application runs inside a Google Cloud environment that has a default service 
account, your application can retrieve the service account credentials to call Google Cloud 
APIs.

我检查了我的应用引擎服务帐户。而且我有一个默认服务帐户并且它处于活动状态。请在此处查看编辑后的图像:

所以我想我的问题是:如果我有一个活动的默认服务帐户,并且我的应用程序在进行 API 调用时应该自动使用默认服务帐户密钥,为什么我会看到此身份验证错误?我做错了什么?

编辑:这是打印错误的代码:

async function updateCrawledOnDateForLink (crawlRequestKey: EntityKey, linkKey: EntityKey): Promise<void> {

  try {
        
    const datastore = new Datastore();
    
    const crawlRequest = await datastore.get(crawlRequestKey)
    
    const brand = crawlRequest[0].brand.replace(/\s/g, "")
    
    await data.Link.update(
      +linkKey.id,
      { crawledOn: new Date() },
      null,
      brand)
        
  } catch (error) {
        console.error('updateCrawledOnDateForLink ERROR:', `CrawlRequest: ${crawlRequestKey.id}`, `Link: ${linkKey.id}`, error.message)
  }
}

我的预测是每次创建一个新的 Datastore() 都会有问题,但请告诉我你的想法。

【问题讨论】:

  • 编辑您的问题并包含生成错误的代码。
  • 让我花一些时间来缩小导致问题的代码块的范围。知道后我会回复代码。
  • 好的,我用有问题的代码更新了帖子。希望你有一些见解。
  • 还有 2 个问题:你能分享你的 app.yaml 文件吗?你能分享你的 package.json 文件吗?谢谢
  • 删除两个不同函数中对全局的新 Datastore() 调用(删除本地新 Datastore() 调用)已导致问题消失。我已将应用程序运行 5 次以上,但从那以后它就没有出现过。

标签: authentication google-app-engine google-cloud-platform google-authentication service-accounts


【解决方案1】:

从几个函数中删除 new Datastore() 解决了问题这一事实表明,问题不在于 App Engine 的身份验证,而在于 Datastore,这证实了您共享的文档。

我认为问题在于,当您出于某种未知原因在代码中创建多个实例时,Datastore 会丢失凭据。

由于您在 cmets 中提到您的代码中实际上并不需要多个 Datastore 实例,因此您的问题的解决方案是在全局变量中使用单个实例并在多个函数中使用该变量。

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 1970-01-01
    • 2020-04-28
    • 2017-07-13
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2016-06-01
    • 2020-03-01
    相关资源
    最近更新 更多