Use a Lambda Function to Reboot EC2 Instance when Unresponsive

By Chris Diggs | August 6, 2020

Scenario: I have an EC2 Instance, t2.micro, that hosts a WordPress site. Every so often, the website becomes non-responsive and the EC2 instance needs to be rebooted.

In this blog post, we’ll create a Lambda function that makes an HTTP Request to the website. If the HTTP Request fails three consecutive times in a row, we’ll reboot the instance. An email or notification will be sent to the responsible party to verify the instance is back up and operational.



  1. Create the Lambda function code – handler.js

'use strict';

const request = require('request');

const AWS = require('aws-sdk');

var ec2 = new AWS.EC2();


const websiteUrl = "https://www.< domain >.com";

const websiteInstanceId = "< ec2-instance-id >"

const healthcheckAttempts = 3;



module.exports.probe = async (event, context, callback) => {


function healthcheck() {

return new Promise((resolve, reject) => {

request(websiteeUrl, function(error, response, body) {

if (error) {

console.error('error:', error);

resolve("Error");

} else {

console.log('statusCode:', response && response.statusCode);

resolve("Success");

}

});

});

}



function bounce_server() {

return new Promise((resolve, reject) => {

var params = {

InstanceIds: [

websiteInstanceId

]

};

ec2.rebootInstances(params, function(err, data) {

if (err) {

console.log(err, err.stack);

resolve("Error: healthcheck and reboot failure.");

} else {

console.log(data);

resolve("Error: healthcheck failure.");

}

});

});

}


for (var i = 0; i < healthcheckAttempts; i++) {

if (await healthcheck() === "Success") {

break;

}

}


//If the health check fails after number of attempts

//Exit the function and send an alert email

if (i == healthcheckAttempts) {

console.log("Bouncing the server..")

callback(await bounce_server());

} else {

console.log("Success: healthcheck passed.");

return;

}


};


  • npm init

  • npm install request

  • npm install aws-sdk



  1. Zip the Lambda function code and deploy to AWS

  • Give the Lambda function enough time to complete the requests – at least five minutes.

  • Make sure to deploy the Lambda function in the same region as the AWS EC2 Instance.

  • The Lambda function will need access to the following IAM Permissions to be able to reboot the instance:

    • "ec2:Reboot*"

  • https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html

  1. Use AWS CloudWatch Events to invoke the Lambda function every 15 minutes


  1. Set up a CloudWatch Alarm to monitor when outages occur (Lambda function failure) and send an email via SNS



comments powered by Disqus