1

I have a AWS Lambda function that checks if a site is online

var http = require('https');
var url = 'https://www.google.com';

exports.handler = function(event, context) {
  http.get(url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
   console.log("Got error: " + e.message);
   context.done(null, 'FAILURE');
  });
}

I would like to reboot an EC2 instance if the website is offline. This is the Lambda function to reboot EC2:

var AWS = require('aws-sdk');
exports.handler = function(event, context) {
 var ec2 = new AWS.EC2({region: 'us-east-1'});
 ec2.rebootInstances({InstanceIds : ['i-xxxxxxxxxxxxxxx'] },function (err, data) {
 if (err) console.log(err, err.stack);
 else console.log(data);
 context.done(err,data);
 });
};

Both functions work. Now I am trying to call the ec2 reboot function when the https request fails.

I have an extremely limited experience with node.js and aws so I tried many different ways but no result.

Can someone point me in the right direction?

Marios
  • 26,333
  • 8
  • 32
  • 52
Kuitogu67
  • 51
  • 7

1 Answers1

0

you can invoke a lambda using the invoke function.

function checkWebsite(url, callback) {
  https
    .get(url, function(res) {
      console.log(url, res.statusCode);
      return callback(res.statusCode === 200);
    })
    .on("error", function(e) {
      return callback(false);
    });
}


var http = require('https');


exports.handler = function(event, context, callback) {
  var url = 'https://www.google.com';
  
  checkWebsite(url, (check) => {

    if (!check) {
      const lambda = new AWS.Lambda();

      const params = {
       FunctionName: "my-function", 
       Payload: '{"instanceId":"instance-1233x5"}'
      };
 
      lambda.invoke(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else console.log(data);           // successful response

        // handle error/ success

        // if you return the error, the lambda will be retried, hence returning a successful response
        callback(null, 'successfully rebooted the instance')

      });

      
    } else {

      
      callback(null, 'successfully completed')
    }
  })
}

Reference: Nodejs function to check if a website working

Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39
  • Thanks, I got that. But still I can't understand how I can invoke the lambda function. I start with my first chunk of code, it returns https failure -> I need to invoke it. Don't understand how – Kuitogu67 Aug 22 '20 at 12:55