Skip to content

Instantly share code, notes, and snippets.

@theigor
Last active May 4, 2020 18:33
Show Gist options
  • Save theigor/140b9954228930afc15bf8760357ad74 to your computer and use it in GitHub Desktop.
Save theigor/140b9954228930afc15bf8760357ad74 to your computer and use it in GitHub Desktop.
Node/Typescript service to get Google Secret Manager secrets by name
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
// I like to define them explicitly so devs know what's out there.
type SECRETS = "SOME_ENV_VAR" | "SOME_OTHER_ONE";
const client = new SecretManagerServiceClient();
export async function getSecret(name: SECRETS) {
// you can get more sophistacted here with different environments but that wasn't needed for my case
if (process.env.NODE_ENV === "production") {
// if your project my-cool-project, the secret name is 'projects/my-cool-project/...'
const real_name = `projects/YOUR-PROJECT-NAME/secrets/${name}/versions/latest`;
const [secret] = await client.accessSecretVersion({ name: real_name });
return Buffer.from(secret.payload.data).toString();
}
else {
// because they're in your .env
return process.env[name];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment