Skip to content Skip to sidebar Skip to footer

Why Can My Code Run In A Standard Node.js File, But Not In A AWS Lambda Function?

What I'm trying to do is create a lambda function where the function calls two commands on an ec2 instance. When I had trouble running this code in a lambda function, I removed the

Solution 1:

You're trying to combine async/await with callbacks. That won't work in a lambda AWS Lambda Function Handler in Node.js. The reason it's working locally, or in a node server, is because the server is still running when the function exits, so the callback still happens. In a Lambda the node process is gone as soon as the lambda exits if you are using async (or Promises), so the callback is not able to be fired.


Solution 2:

Solution based on Jason's Answer:

const AWS = require('aws-sdk');
const ssm = new AWS.SSM();


exports.handler = async (event,context) => {

AWS.config.update({region:'us-east-1'});
  const params = {
  DocumentName: 'AWS-RunShellScript', /* required */
  InstanceIds: ['i-xxxxxxxxxxxxxx'],
  Parameters: {
    'commands': [
      'mkdir /home/ec2-user/testDirectory',
      'php /home/ec2-user/helloWorld.php'
      /* more items */
    ],
    /* '<ParameterName>': ... */
  }
};


  const ssmPromise = new Promise ((resolve, reject) => {
    ssm.sendCommand(params, function(err, data) {
  if (err) {
    console.log("ERROR!");
    console.log(err, err.stack); // an error occurred
    context.fail(err);
  }
  else {
  console.log("SUCCESS!");
  console.log(data);
  context.succeed("Process Complete!");
  }            // successful response
  });
});


console.log(ssmPromise);   


  const response = {
    statusCode: 200,
    ssm: ssm
  };

  return response;
};

Post a Comment for "Why Can My Code Run In A Standard Node.js File, But Not In A AWS Lambda Function?"