Skip to content

Instantly share code, notes, and snippets.

@dominicbartl
Created March 18, 2022 08:34
Show Gist options
  • Save dominicbartl/826dfc99d5ee25b41afebef00671f08c to your computer and use it in GitHub Desktop.
Save dominicbartl/826dfc99d5ee25b41afebef00671f08c to your computer and use it in GitHub Desktop.
Fetch secrets from GCP Secret Manager and write them to an env file
#!/usr/bin/env node
const {SECRETS} = require('../build/dist/functions/secrets');
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const {join} = require('path');
const {writeFileSync} = require('fs')
const client = new SecretManagerServiceClient();
const projectId = process.argv[2];
const outputFile = join(__dirname, '..', `.env.${projectId}`);
async function readSecret(projectId, secretName) {
// Access the secret.
const name = `projects/${projectId}/secrets/${secretName}/versions/latest`;
console.log('Accessing', name);
const [accessResponse] = await client.accessSecretVersion({
name: name,
});
return accessResponse.payload.data.toString('utf8');
}
async function generateEnvData(projectId) {
const lines = await Promise.all(SECRETS.map(async (secretName) => {
const value = await readSecret(projectId, secretName);
return `${secretName}=${value}`;
}));
return lines.join('\n');
}
async function writeEnvFile(projectId, target) {
const content = await generateEnvData(projectId);
writeFileSync(target, content, 'utf8');
return target;
}
writeEnvFile(projectId, outputFile)
.then((file) => {
console.log('Successfully written', file);
process.exit(0);
})
.catch((err) => {
console.error(err.message);
process.exit(1);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment