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
The third argument, callback , is a function that you can call in non-async handlers to send a response. The callback function takes two arguments: an Error and a response. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker.
Short description. There are three reasons why retry and timeout issues occur when invoking a Lambda function with an AWS SDK: A remote API is unreachable or takes too long to respond to an API call. The API call doesn't get a response within the socket timeout.
Install and package the latest version of the AWS SDK Note: Deployment packages must be compatible with the Lambda runtime that you're using. It's a best practice to use the same operating system for your runtime that's specified in AWS Lambda runtimes.
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();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With