getSecretValue callback is not working in AWS Lambda

Viewed 5474

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

1 Answers

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();
};
Related