Last active
May 2, 2022 18:10
-
-
Save MichaelSolati/4f4257325e805858241e350f53c2e9f9 to your computer and use it in GitHub Desktop.
Takes secrets stored in Google Cloud's Secret Manager and save's it into a `.env` file.
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
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager'); | |
const client = new SecretManagerServiceClient(); | |
const cloudSecrets = async () => { | |
if (!process.env.PROJECT_ID) { | |
return console.warn( | |
'No Google Cloud Project ID found, no .env file is being generated.' | |
); | |
} | |
console.log('Generating .env file.'); | |
const project = `projects/${process.env.PROJECT_ID}`; | |
let dotenv = ''; | |
const fetchedSecrets = []; | |
const [secretsList] = await client.listSecrets({parent: project}); | |
for (const secretItem of secretsList) { | |
const key = secretItem.name.split('/').pop(); | |
const [versions] = await client.listSecretVersions({ | |
parent: secretItem.name, | |
}); | |
const version = versions.find(v => v.state === 'ENABLED'); | |
if (version) { | |
const [accessedSecret] = await client.accessSecretVersion({ | |
name: version.name, | |
}); | |
const value = accessedSecret.payload.data.toString(); | |
dotenv += `${key}=${value}\n`; | |
fetchedSecrets.push(key); | |
} | |
} | |
require('fs').writeFileSync('.env', dotenv); | |
console.log( | |
`The following environment variables have been added to the generated .env file: ${fetchedSecrets.join( | |
', ' | |
)}` | |
); | |
}; | |
cloudSecrets().catch(e => { | |
console.warn('Ooops, there was an error in generating the .env file.', e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment