从Google Cloud Storage提供Google客户服务帐户的keyFilename

问题描述 投票:1回答:1

要连接到与Google Cloud Function不同的GCP项目中存在的Google Cloud BigQuery,我将按如下方式创建BigQuery客户端:

const {BigQuery} = require('@google-cloud/bigquery');
const options = {
    keyFilename: 'path/to/service_account.json',
    projectId: 'my_project',
  };
const bigquery = new BigQuery(options);

但是我不想将service_account.json存储在我的Cloud Function中,而是将服务帐户存储在Google Cloud Storage中,并在上面的keyFilename中提供Google Cloud Storage路径。如果可以提供google cloud存储路径而不是本地路径,我找不到任何文档。

google-bigquery google-cloud-functions service-accounts google-cloud-iam
1个回答
2
投票

您无法提供Google云存储路径。假设您具有正确的权限来部署功能以从存储桶访问Blob(key.json文件),则可以将文件从Google Cloud Storage下载到Cloud Function的\tmp目录。

Downloading objects

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

// Creates a client
const storage = new Storage();

async function downloadFile() {
  const options = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: \tmp\key.json,
  };

  // Downloads the file
  await storage
    .bucket(bucketName)
    .file(srcFilename)
    .download(options);

  console.log(
    `gs://${bucketName}/${srcFilename} downloaded to ${destFilename}.`
  );
}

downloadFile().catch(console.error);

const options = {
    keyFilename: '/tmp/key.json',
    projectId: 'my_project',
  };

const bigquery = new BigQuery(options);



一个更好的解决方案是将key.json文件与Google Secret Manager存储在一起。然后,将角色secretmanager.secretAccessor分配给您的云功能,并从您的云功能访问机密。

Creating secrets and versions

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret/versions/5';
// const name = 'projects/my-project/secrets/my-secret/versions/latest';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function accessSecretVersion() {
  const [version] = await client.accessSecretVersion({
    name: name,
  });

  // Extract the payload as a string.
  const payload = version.payload.data.toString('utf8');

  // WARNING: Do not print the secret in a production environment - this
  // snippet is showing how to access the secret material.
  console.info(`Payload: ${payload}`);
}

accessSecretVersion();

© www.soinside.com 2019 - 2024. All rights reserved.