UNPKG

secrets2env

Version:

Retrieves secrets from AWS Secrets Manager and writes them as an env file.

110 lines (94 loc) 2.46 kB
#!/usr/bin/env node /* eslint no-console: off */ const aws = require('aws-sdk'); function setCredentials(profile) { const { SharedIniFileCredentials } = aws; const credentials = new SharedIniFileCredentials({profile}); aws.config.credentials = credentials; return; } function showHelp(exitCode) { const message = ` Usage: secrets2env [OPTIONS] SecretId Options: -h, --help Display help screen -f, --format Currently only takes JSON (Default=.env file format) -p, --profile If using local ~/.aws credentials -r, --region Region to use for secrets lookup -v, --version Display version `; console.log(message); if (exitCode !== undefined) { process.exit(exitCode); } } function evalCmdl(){ const argv = require('minimist')(process.argv.slice(2), { 'string' : [ 'format', 'profile', 'region' ], 'boolean' : true, 'alias' : { 'format' : 'f', 'profile' : 'p', 'region' : 'r', 'help' : 'h', 'version' : 'v' } }); if (argv.version) { const { version } = require('./package.json'); console.log(`secrets2env, Version ${version}`); process.exit(0); } if (argv.help) { showHelp(0); } if (!argv._[0]) { console.error('Must specify a SecretId!'); process.exit(1); } const format = (argv.format || '').toLowerCase(); if (format !== '' && format !== 'json') { console.error(`Invalid format: ${argv.format}`); process.exit(1); } const SecretId = argv._.shift(); const { profile, region } = argv; return { profile, region, format, SecretId } ; } function getSecretValue(SecretId, region) { return new Promise((resolve, reject) => { const { SecretsManager } = aws; const sm = new SecretsManager({ region }); sm.getSecretValue({ SecretId }, (err, data) => { if (err) { return reject(err); } return resolve(JSON.parse(data.SecretString)); }); }); } ((async () => { const { profile, region, SecretId, format } = evalCmdl(); if (profile) { setCredentials(profile); } try { const s = await getSecretValue(SecretId, region); if (format === 'json') { console.log(JSON.stringify(s, null, 3)); } else { for (let envvar in s) { console.log(`${envvar}=${s[envvar]}`); } } } catch(e) { console.error(e); process.exit(1); } })());