4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Cloud Functions(Node.js)でberglasのsm://形式の秘密情報を展開する方法

Posted at

本文

Cloud Runでは sm://<project_id>/<secret_name> の形式で環境変数をセットして起動すれば自動的にSecretManagerから秘密情報を取得して展開してくれます。(言語不問)

同様の機能がCloud Functionsにもあったらいいなと思ったんですが、Go言語版のみしかサポートされていなかったので、Node.js版を作成しました。

const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');

async function resolveSecret(element) {
  const client = new SecretManagerServiceClient();
  const [, , projectId, secretName] = element.split('/');
  const name = `projects/${projectId}/secrets/${secretName}/versions/latest`;

  const [version] = await client.accessSecretVersion({
    name: name,
  });
  return version.payload.data.toString();
}

async function substituteSecrets() {
  const resolved = await Promise.all(
    Object.entries(process.env)
      .filter(([_, element]) => element.startsWith('sm://'))
      .map(async ([key, element]) => [key, await resolveSecret(element)])
  );

  for (const [key, element] of resolved) {
    process.env[key] = element;
  }
}

参考

https://github.com/GoogleCloudPlatform/berglas
https://www.npmjs.com/package/@google-cloud/secret-manager

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?