AWS SecretsManager is a service that allows you to store encrypted secrets in the cloud as raw strings or JSON docs.
Storing secrets as JSON allows you to store ENV settings, similar to a .env
file.
Using the aws-sdk
library for NodeJS, we can update our application's process.env
with the encrypted environment.
npm install aws-sdk
Using the promise-ified version of the getSecretValue()
function, we can update the process.env
object with the response of the AWS resource.
'use strict';
const AWS = require('aws-sdk');
const AWS_SECRET = process.env.AWS_SECRET;
const secretsmanager = new AWS.SecretsManager();
secretsmanager.getSecretValue({SecretId: AWS_SECRET}).promise().then((res) => {
Object.assign(process.env, JSON.parse(res.SecretString));
return process.env;
});
When deploying express apps to AWS Lambda you can establish your ENV before handling the HTTP request.
'use strict';
const AWS = require('aws-sdk');
const awsServerlessExpress = require('aws-serverless-express');
const secretsmanager = new AWS.SecretsManager();
const AWS_SECRET = process.env.AWS_SECRET;
let server;
const createServer = async (options) => {
// Get AWS secret JSON string
const secret = await secretsmanager.getSecretValue(options).promise();
// Update ENV
Object.assign(process.env, JSON.parse(secret.SecretString));
// Import express app & create server
server = awsServerlessExpress.createServer(require('./app'));
return server;
}
// Export Lambda handler
exports.handler = (event, context) => {
Promise.resolve(server || createServer({SecretId: AWS_SECRET})).then((server) => {
awsServerlessExpress.proxy(server, event, context)
});
};
can you paste a code example?
I think you should be able to do something like: