bigquery 使用 text\string 中的服务帐户而不是文件路径进行身份验证

bigquery authenticating with service account from text\string and not file path


我在用 this nodejs bigquery client

我在 string\text 中有服务帐户 json,出于安全原因,我想避免将其写入临时文件。
是否可以选择 new BigQuery() 并将服务帐户作为字符串而不是文件路径提供?
无法在那里找到此选项,在所有示例中都需要提供文件路径或导出 GOOGLE_APPLICATION_CREDENTIALS 变量。

谢谢。

可以将服务帐户中的值用作身份验证字符串。您可以使用 BigQueryOptions 并传递凭证对象。凭据对象将需要 client_emailprivate_key,它们可以在您的服务帐户 json.

中找到

使用sample code you linked in your questionBigQueryOptions可以这样实现

const creds = {
        client_email: 'your_service_account@project-id.iam.gserviceaccount.com',
        private_key: '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n'
};

const bigquery = new BigQuery(credentials=creds);

整个代码将是:

const {BigQuery} = require('@google-cloud/bigquery');

const creds = {
        client_email: 'your_service_account@project-id.iam.gserviceaccount.com',
        private_key: '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n'
};

const bigquery = new BigQuery(credentials=creds);

async function query() {
  // Queries the U.S. given names dataset for the state of Texas.

  const query = `SELECT name
    FROM \`bigquery-public-data.usa_names.usa_1910_2013\`
    WHERE state = 'TX'
    LIMIT 100`;

  // For all options, see https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query
  const options = {
    query: query,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
  };

  // Run the query as a job
  const [job] = await bigquery.createQueryJob(options);
  console.log(`Job ${job.id} started.`);

  // Wait for the query to finish
  const [rows] = await job.getQueryResults();

  // Print the results
  console.log('Rows:');
  rows.forEach(row => console.log(row));
}
query()

输出片段: