Auto Restart Your EC2 Instance with Lambda

I use my blog a lot for testing and a side effect of that is sometimes it gets turned off unexpectedly. To counteract that and ensure more reliability here’s a simple script you can run with AWS Lambda using CloudWatch Events.

'use strict';

const aws = require('aws-sdk');
aws.config.region = 'us-west-2';
const ec2 = new aws.EC2({apiVersion: '2016-11-15'});
const ses = new aws.SES({apiVersion: '2010-12-01'});

function send_notice() {
    var params = {
        Destination: {
            ToAddresses: [
                "[email protected]"
            ]
        },
        Message: {
            Body: {
                Html: {
                    Data: 'Your server has been restarted.'
                },
                Text: {
                    Data: 'Your server has been restarted.'
                }
            },
            Subject: {
                Data: 'Server Restart'
            }
        },
        Source: '[email protected]'
    };
    ses.sendEmail(params, function(err, data) {
       if (err) console.log(err, err.stack);
       else console.log(data);
    });
}

exports.handler = (event, context, callback) => {
    
  var myImportantInstanceId = 'i-554e304d';
  var params = {
    InstanceIds: [
      myImportantInstanceId
    ]
  };

  /*
   * Check Status of Instance
   */
  ec2.describeInstanceStatus(params, function(err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {

        /*
         * Start Instance if not Running
         */
        var state = data.InstanceStatuses[0].InstanceState.Name;
        if ( state !== 'running' ) {
            ec2.startInstances(params, function(err, data) {
                if (err) {
                    console.log(err, err.stack);
                } else {
                    console.log(data);
                    send_notice();
                }
            });
        }
    }
  });

};

After setting up the Lambda function its just a couple clicks to setup a cloudwatch event to trigger the lambda function when a instance is stopped.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.