Within S3, there exists a hello.js file that includes the following code snippet:
function greet() {
console.log(" From Greetings: ");
}
An AWS Lambda function written in NodeJS is attempting to access and execute this script. Despite having the necessary permissions to retrieve the file from S3, the outcome of calling exec remains unclear. Although no errors are thrown, the expected output of "From Greetings" does not appear in the logs.
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const { exec } = require('child_process');
exports.handler = async (event, context) => {
const s3Bucket = 'monitor-state';
const s3Key = 'hello.js';
const params = { Bucket: s3Bucket, Key: s3Key };
try {
const data = await s3.getObject(params).promise();
const script = data.Body.toString();
// Execute the script
exec(`node -e "${script}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Script execution error: ${error}`);
return context.fail('Error executing the script.');
} else {
console.log('Script execution output:');
console.log(stdout);
return context.succeed('Script executed successfully.');
}
});
} catch (error) {
console.error('Error fetching the script from S3:', error);
return context.fail('Error executing the script.');
}
};
Despite experimenting with different approaches for invoking exec, none have resulted in the desired functionality.