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:
// Get the latest version of the secret
const secretLatest = GCSecretManager.get("secret-key", {
project: "project-id",
});
// Get the latest version of the secret
const secretV2 = GCSecretManager.get("secret-key", {
project: "project-id",
version: 2,
});
// Instead of the config, specify project via chaining:
const anotherSecretV3 = GCSecretManager.setProject("project-id")
.setVersion(3)
.get("another-secret-key");
// Set secret. A new one will be created if it doesn't exist
// or, if it does, a new version for the existing one.
GCSecretManager.set("secret-key", "secret-value", { project: "project-id" });
// Directly call the Secret Manager API
// Get the latest version of the secret
const oneMoreSecretLatest = GCSecretManager.getSecret(
"project-id",
"one-more-secret-key"
);
// Create a new secret
GCSecretManager.createSecret("project-id", "new-secret-key");
// Create a new version of a secret
GCSecretManager.createSecretVersion(
"project-id",
"new-secret-key",
"new-secret-value"
);
Create an Instance
You can create an instance to provide the configuration only once and use it multiple times:
// Initialize
const MANAGER = GCSecretManager.init({ project: "project-id" });
// You can also use chaining to initialize the manager
const MANAGER = GCSecretManager.init().setProject("project-id");
// Retrieve the latest secret version
const secret = MANAGER.get("secret-key");
// Set a secret
MANAGER.set("secret-key", "secret-value");
// The direct methods will work the same way as in the examples above
const oneMoreSecretLatest = MANAGER.getSecret(
"project-id",
"one-more-secret-key"
);
As a SecretService Storage
GCSecretManager can also work as a storage layer for the SecretService library, combining their benefits:
const storage = GCSecretManager.init({ project: "project-id" });
const SECRETS = SecretService.init({ storage });
const secretValue = SECRETS.getSecret("API_KEY");
Contributions are welcome. Feel free to submit pull requests or issues on GitHub.
Top comments (0)