Skip to content

Instantly share code, notes, and snippets.

Created March 9, 2020 18:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
GCP Secret Manager to get runtime environment credentials for multiple environments
import {SecretManagerServiceClient} from '@google-cloud/secret-manager';
import * as admin from 'firebase-admin';
const client = new SecretManagerServiceClient();
let credentials: admin:;
let credentials1: admin:;
let credentials2: admin:;
export const db = async (type: string): Promise<admin:> => {
switch (type) {
case 'credentials':
if (credentials) {
return credentials;
} else {
credentials = await getCredential(process.env.C1, type);
return credentials;
case 'credentials1':
if (credentials1) {
return credentials1;
} else {
credentials1 = await getCredential(process.env.C2, type);
return credentials1;
case 'credentials2':
if (credentials2) {
return credentials2;
} else {
credentials2 = await getCredential(process.env.C3, type);
return credentials2;
async function getCredential(path: string, type: string): Promise<admin:> {
try {
const tempCredential: admin:;
const [version] = await client.accessSecretVersion({
name: path,
const result: any = JSON.parse(;
const params = {
type: result.type,
projectId: result.project_id,
privateKeyId: result.private_key_id,
privateKey: result.private_key,
clientEmail: result.client_email,
clientId: result.client_id,
authUri: result.auth_uri,
tokenUri: result.token_uri,
authProviderX509CertUrl: result.auth_provider_x509_cert_url,
clientC509CertUrl: result.client_x509_cert_url,
tempCredential.admin = admin.initializeApp({
credential: admin.credential.cert(params),
storageBucket: `gs://${result.project_id}`,
}, type);
return tempCredential;
} catch (e) {
console.error('credentials error. Check if the app engine default service account has scret manager accessor' +
' access', e);
return null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment