JonathanGailliez JonathanGailliez - 2 months ago 59
Node.js Question

AWS Lambda: How to store secret to external API?

I'm building a monitoring tool based on AWS Lambda. Given a set of metrics, the Lambdas should be able to send SMS using Twilio API. To be able to use the API, Twilio provide an account SID and an auth token.

How and where should I store these secrets?

I'm currently thinking to use AWS KMS but there might be other better solutions.


here is what I've come up with. I'm using AWS KMS to encrypt my secrets into a file that I upload with the code to AWS Lambda. I then decrypt it when I need to use them.

Here are the steps to follow.

First create a KMS key. You can find documentation here:

Then encrypt your secret and put the result into a file. This can be achieved from the CLI with:

aws kms encrypt --key-id some_key_id --plaintext "This is the scret you want to encrypt" --query CiphertextBlob --output text | base64 -D > ./encrypted-secret

You then need to upload this file as part of the Lambda. You can decrypt and use the secret in the Lambda as follow.

var fs = require('fs');
var AWS = require('aws-sdk');
var kms = new AWS.KMS({region:'eu-west-1'});

var secretPath = './encrypted-secret';
var encryptedSecret = fs.readFileSync(secretPath);

var params = {
  CiphertextBlob: encryptedSecret

kms.decrypt(params, function(err, data) {
  if (err) console.log(err, err.stack);
  else {
    var decryptedScret = data['Plaintext'].toString();

I hope you'll find this useful.

Best regards, Jonathan