GCP Secret Manager to get runtime environment credentials for multiple environments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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