AWS Lambda: How to store secret to external API?

前端 未结 5 567
时光说笑
时光说笑 2020-12-22 19:11

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 provi

5条回答
  •  天涯浪人
    2020-12-22 20:00

    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: http://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html

    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 decryptedSecret = data['Plaintext'].toString();
        console.log(decryptedSecret);
      }
    });
    

    I hope you'll find this useful.

提交回复
热议问题