8

I'm trying to retrieve Secret Value from AWS Secret Manager using aws-sdk for Javascript, I'm using the code snippet provided by Secret Manager, I have included this code in Lambda function, but I can't see any console logs defined inside the callback function. Here's the lambda code:

exports.handler = async (event, context) => {
    const AWS = require('aws-sdk');
    const client = new AWS.SecretsManager({ region: "eu-west-2" });
    let secret;
    let decodedBinarySecret;

    console.log('STARTED');

    client.getSecretValue({ SecretId: "MagellanDev" }, function (err, data) {
        if (err) {
            console.log('Got Error: ', err.code);
            throw err;
        }
        else {
            if ('SecretString' in data) {
                secret = data.SecretString;
            } else {
                let buff = new Buffer(data.SecretBinary, 'base64');
                decodedBinarySecret = buff.toString('ascii');
            }
        }

        console.log("SECRET: ", secret);
        console.log("DECODEBINARYSECRET: ", decodedBinarySecret)
    });

    console.log('ended');

};

Output:

Started

ended

kzrfaisal
  • 1,355
  • 5
  • 15
  • 26

1 Answers1

10

The problem is that you have specified the function handler as async. If you want to use callbacks, then use the older style function handler:

exports.handler = function(event, context, callback) {
  // ...
}

The code has exited before the getSecretValue() function has completed and had a chance to make the callback. And because your function is async and you did not return a Promise, the Lambda runtime is not waiting.

I would move away from the older callback-style code and move to the newer async/await-style code, for example:

const AWS = require('aws-sdk');
const client = new AWS.SecretsManager({region: 'us-east-1'});

exports.handler = async (event, context) => {
    const params = {SecretId: secretName};
    return client.getSecretValue(params).promise();
};
jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 1
    I'm not sure where decode_secret is defined, but you can just use let result = await rc; return result; instead. – nachbar Jun 21 '20 at 00:10
  • @nachbar Provide another answer with your approach? – rainabba Mar 18 '21 at 21:49
  • @rainabba, it has been a while since I looked at this, but take a look at the previous versions of this answer (click the "edited" link on the answer) to see what I was suggesting. – nachbar Mar 25 '21 at 22:03
  • thanks for the `.promise()`. I scratched my head for 2 hours before I understood what I missed. – sbr Aug 19 '22 at 16:13