Get secrets in AWS lambda node.js

4.4k Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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 = .....
4
On

Looking at your question seems you are not able to read response from retrieve_secret('mysecret') method as you have mentioned it return promise, you can read it by using .then() after promise. Try doing this -

xxx.then(res => {
    console.log(res)
})

Or here is the code to call get your secret details:

import AWS from "aws-sdk";

getSecretValue(secretName: string): Promise<string> {
        const client = new AWS.SecretsManager({ 
            region: '',
            accessKeyId: '',
            secretAccessKey: '',
        });
        const secretId = "secretName";
        return new Promise((resolve, reject) =>
            client.getSecretValue({ SecretId: secretId }, (err, data) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(data.SecretString);
                }
            })
        );
    }