serverless-mysql
serverless-mysql copied to clipboard
using secrets manager in lambda
Does anyone know how you would require/initialize mysql outside the handler function if I am using secretsmanager to get the credentials inside my lambda?
Is this a case where I want to initialize with no config and then call config inside the lambda after I have fetched the credentials?
@wetzelb That's the way I dealt with it. Had issues with running the code straight from initialization so I moved it to actual process with a flag for first-run init. Will provide a snippet once I'm home
[Edit] The snippet I promised you. Most likely lots of room for improvement but so far works for me:
const secretName = process.env.secret;
let config;
const mysql = require('serverless-mysql')();
checkSecretsAndInit = async function() {
if (mysql.getConfig().host === undefined) {
config = await secretStore.getSecret(secretName); // Could set it to local variable so the secret won't be shared as variable between calls, but you can pry the stuff from mysql instance either way
mysql.config({
host: config.host,
user: config.username,
password: config.password,
database: config.dbname,
port: config.port
});
console.log("SUCCESSFULLY CONFIGURED MYSQL CONNECTION TO" + config.host);
}
console.log("MYSQL CONNECTION STATS: host: " + config.host + ", port: " + config.port + ", dbname:" + config.dbname);
}
app.get('/process/getUser', async (req, res, next) => {
await checkSecretsAndInit();
... // LOGIC GOES HERE
}
I'm running a proxy server in my lambda, you could easily add the line directly to the handler if you're following the one endpoint - one function schema.
this won't work in lambda#edge, you need ssm and you just need the aws-sdk
const AWS = require('aws-sdk');
const SSM = new AWS.SSM({ apiversion: '2014-11-06' });
const parameter = await SSM.getParameter()