post-thumb

Access Google Cloud Secret Manager via Google Apps Script

There are many ways to store secrets, such as tokens, passwords, and API keys, in Google Apps Script, but they are not created equal. Some are safer than others. One way to deal with this challenge is to store the secrets externally and access them on demand.

GCSecretManager (GitHub ) is a Google Apps Script library that allows you to store secrets in Google Cloud Secret Manager . The library also works as a storage for SecretService library. Let’s look at three ways to use it.

If you find this library useful, please give the repository a star and share the link with others.


Use Library Directly

You can use the library directly without initializing an instance:

 1// Get the latest version of the secret
 2const secretLatest = GCSecretManager.get("secret-key", {
 3  project: "project-id",
 4});
 5
 6// Get the latest version of the secret
 7const secretV2 = GCSecretManager.get("secret-key", {
 8  project: "project-id",
 9  version: 2,
10});
11
12// Instead of the config, specify project via chaining:
13const anotherSecretV3 = GCSecretManager.setProject("project-id")
14  .setVersion(3)
15  .get("another-secret-key");
16
17// Set secret. A new one will be created if it doesn't exist
18// or, if it does, a new version for the existing one.
19GCSecretManager.set("secret-key", "secret-value", { project: "project-id" });
20
21// Directly call the Secret Manager API
22
23// Get the latest version of the secret
24const oneMoreSecretLatest = GCSecretManager.getSecret(
25  "project-id",
26  "one-more-secret-key"
27);
28
29// Create a new secret
30GCSecretManager.createSecret("project-id", "new-secret-key");
31// Create a new version of a secret
32GCSecretManager.createSecretVersion(
33  "project-id",
34  "new-secret-key",
35  "new-secret-value"
36);

Create an Instance

You can create an instance to provide the configuration only once and use it multiple times:

 1// Initialize
 2const MANAGER = GCSecretManager.init({ project: "project-id" });
 3
 4// You can also use chaining to initialize the manager
 5const MANAGER = GCSecretManager.init().setProject("project-id");
 6
 7// Retrieve the latest secret version
 8const secret = MANAGER.get("secret-key");
 9
10// Set a secret
11MANAGER.set("secret-key", "secret-value");
12
13// The direct methods will work the same way as in the examples above
14const oneMoreSecretLatest = MANAGER.getSecret(
15  "project-id",
16  "one-more-secret-key"
17);

As a SecretService Storage

GCSecretManager can also work as a storage layer for the SecretService library, combining their benefits:

1const storage = GCSecretManager.init({ project: "project-id" });
2const SECRETS = SecretService.init({ storage });
3
4const secretValue = SECRETS.getSecret("API_KEY");

Contributions are welcome. Feel free to submit pull requests or issues on GitHub .