【问题标题】:pass default credentials to BigQuery using Nodejs使用 Nodejs 将默认凭据传递给 BigQuery
【发布时间】:2020-02-10 17:39:20
【问题描述】:

我正在尝试在 BigQuery 中创建一个新表。我已遵循这些说明https://codelabs.developers.google.com/codelabs/cloud-bigquery-nodejs/index.html?index=..%2F..index#9 并正确定义了我的用户和角色。

我创建了一个节点项目,安装了 google 依赖项并具有以下代码:

 const {BigQuery} = require('@google-cloud/bigquery');
 const bigquery = new BigQuery({
   projectId: 'myproject-develop-3fcb6',
  private_key_id: "11111111111",
  client_email: "myuser-bigquery-sa@myproject-develop-3fcb6.iam.gserviceaccount.com",
  client_id: "212111112",
  });

这就是我创建数据集和表的方式:

 module.exports = {
  createTable: ({ datasetId, tableId, schema, partitionBy}) => {
    const options = { schema };
    if (partitionBy) {
     options.timePartitioning = {
     field: partitionBy
   };
  }

  return new Promise((resolve, reject) => {
    resolve();
     bigquery
    .dataset(datasetId)
    .createTable(tableId, options)
    .then(results => resolve(results[0]))
    .catch(err => {
      handleError(err);
      reject(err);
    });
   });
  },
 };

当我运行我的 createTableFunction 并传入数据集名称、表名、架构时,我立即收到以下错误

ERROR: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.

如何将我的默认凭据传递给 BigQuery,以便我可以在 node.js 中执行 CRUD 操作?谢谢

【问题讨论】:

    标签: node.js google-bigquery


    【解决方案1】:

    在您提到的教程中,这个 gcloud 命令创建了一个 key.json:

       gcloud iam service-accounts keys create ~/key.json --iam-account  my-bigquery-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com
    

    那么就可以使用下面的代码了:

     // Create a BigQuery client explicitly using service account credentials.
     // by specifying the private key file.
     const {BigQuery} = require('@google-cloud/bigquery');
    
     const options = {
       keyFilename: 'path/to/key.json',
       projectId: 'my_project',
     };
    
    const bigquery = new BigQuery(options);
    

    Authenticating With a Service Account Key File

    我不知道你在哪里运行你的代码,但是在教程中有一行你设置了环境变量,因此你不需要在你的代码中使用 key.json 文件进行身份验证:

       export GOOGLE_APPLICATION_CREDENTIALS="/home/${USER}/key.json"
    

    GCP 客户端库使用一种称为应用程序默认值的策略 凭据 (ADC) 来查找您的应用程序的凭据。当你的 代码使用客户端库,该策略会检查您的凭据 按以下顺序:

    首先,ADC 检查环境变量是否 GOOGLE_APPLICATION_CREDENTIALS 已设置。如果设置了变量,ADC 使用变量指向的服务帐户文件。下一个 部分描述了如何设置环境变量。

    如果未设置环境变量,ADC 使用默认服务 Compute Engine、Kubernetes Engine、Cloud Run、App Engine、 和 Cloud Functions 为在这些平台上运行的应用程序提供 服务。

    如果 ADC 无法使用上述任一凭据,则会发生错误。

    【讨论】:

    • 从 GCP 下载了 key.json。那是我的问题。我从终端复制了内容。大禁忌。谢谢
    • 如果我的回答对您有帮助,请将其标记为已接受,以便更好地为社区提供可见性。
    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多