Google Apps 脚本访问 Secret Manager

Wen*_*Hao 7 google-apps-script google-cloud-platform

我正在构建一个需要访问 mysql 的数据工作室连接器(应用程序脚本)。

我将所有凭据存储在 GCP Secret Manager 中,并希望我的应用程序脚本从 Secret Manager 获取凭据。

我检查了https://developers.google.com/apps-script文档,但找不到访问 Secret Manager 的相关类。

Apps 脚本获取存储在 Secret Manager 中的凭据的最佳方式是什么?

小智 9

我还需要从 Secret Manager 读取机密,以避免 Google App 脚本中的硬编码值。在 GCP 开发者控制台的 Secret Manager 中添加秘密值后,我启用了 Secret Manager API。

这是我的解决方案:

首先,在应用程序脚本编辑器中打开“项目设置”菜单(左侧面板上的设置齿轮图标)并勾选复选框:

    "Show appsscript.json manifest file in editor"
Run Code Online (Sandbox Code Playgroud)

这将使appscript.json文件在主Code.gs附近的项目文件中可见。然后将这些行添加到appscript.json中的现有字典中:

"oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/cloud-platform"
]
Run Code Online (Sandbox Code Playgroud)

这将为您的项目启用必要的范围。我正在从 Secret Manager 读取 API 密钥,因此我在Code.gs中添加了getAPIKey()函数 :

function getAPIKey() {
  let token, endpoint, response;
  endpoint = `https://secretmanager.googleapis.com/v1/projects/<project_id>/secrets/<secret_name>/versions/<version_number>:access`;
  token = ScriptApp.getOAuthToken();
  response = UrlFetchApp.fetch(endpoint, {
    headers: {
      Authorization: 'Bearer ' + token,
      Accept: 'application/json',
    }
  });
  var decodedAPIKey = Utilities.base64Decode(JSON.parse(response.getContentText())['payload']['data']);
  var apiKey = Utilities.newBlob(decodedAPIKey).getDataAsString()
  return apiKey;
}
Run Code Online (Sandbox Code Playgroud)

Google Cloud OAuth 令牌用于验证此脚本以访问 Secret Manager。第一次运行脚本时,您还需要手动进行授权,但只需一次。

请记住添加您的project_idsecret_nameversion_number。打开您的秘密值时,您将在开发者控制台的秘密管理器中找到此信息。

然后在需要秘密值的地方调用此函数。


小智 1

回顾一下以获得更好的可见性:
当您需要在 Google Cloud 中存储机密(密码、证书、私钥等)时,可以使用Secret Manager
要让您的应用程序自动安全地检索它们,请使用Secret Manager API。可以使用 REST 或 gRPC API、Google Cloud或您自己的库来访问它们。