Note (2026): This post is from 2016 and uses the old
aws-sdkv2 Node.js API. The pattern still works, but for new projects use@aws-sdk/client-ec2and@aws-sdk/client-sesfrom the v3 SDK. Instance IDs and email addresses in the code below are placeholders — substitute your own.
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: [
"your-number@txt.att.net"
]
},
Message: {
Body: {
Html: {
Data: ‘Your server has been restarted.’
},
Text: {
Data: ‘Your server has been restarted.’
}
},
Subject: {
Data: ‘Server Restart’
}
},
Source: ‘no-reply@yourdomain.com’
};
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-0123456789abcdef0’;
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.
