Search code examples
node.jsamazon-web-servicesaws-lambdasecret-manager

Get secrets in AWS lambda node.js


Can anyone provide a simple, complete node.js lambda function where I can get a secret from secrets manager and use it? I am struggling with the async/await process. I have already tried several suggestions from other posts, but all of them, at the end, can't really use the secret in the main function. For example, I have a main function and call a second function to retrieve the secret:

xxx = retrieve_secret('mysecret');

Then, in the retrieve_secret function I am able to retrieve the secret, I can print it using console.log, but when I try to use it in the main function, it says "Promise ".

Please, help. Thanks in advance!


Solution

  • So, after a few days working on it, I was finally able to solve it :) Here is the code that worked for me:

    exports.handler = async (event, context, callback) => {
    
       // Get Secret
       var AWS       = require('aws-sdk');
       var MyPromise = new AWS.SecretsManager();
    
       var Vsecret   = await MyPromise.getSecretValue({
          SecretId: 'enter-the-secret-id-here'
          }).promise();
    
       var MyOpenSecret = JSON.parse(Vsecret.SecretString);
    
       // From here, we can use the secret:
       var Vhost     = MyOpenSecret.host;
       var Vuser     = MyOpenSecret.username;
       var Vpassword = MyOpenSecret.password; 
       var Vdatabase = .....