Skip to content

Instantly share code, notes, and snippets.

@shashkiranr
Created March 9, 2020 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shashkiranr/04b8f0c9c21f1fb4ed1654e83d26f473 to your computer and use it in GitHub Desktop.
Save shashkiranr/04b8f0c9c21f1fb4ed1654e83d26f473 to your computer and use it in GitHub Desktop.
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: admin.app.App;
let credentials1: admin: admin.app.App;
let credentials2: admin: admin.app.App;
export const db = async (type: string): Promise<admin: admin.app.App> => {
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: admin.app.App> {
try {
const tempCredential: admin: admin.app.App;
const [version] = await client.accessSecretVersion({
name: path,
});
const result: any = JSON.parse(version.payload.data.toString());
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}.appspot.com`,
}, 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