Skip to content

Instantly share code, notes, and snippets.

@binhp
Last active February 11, 2024 01:50
Show Gist options
  • Save binhp/d3566f77173b3c2a07979ae839c9e197 to your computer and use it in GitHub Desktop.
Save binhp/d3566f77173b3c2a07979ae839c9e197 to your computer and use it in GitHub Desktop.
AWS EC2 Schedule to Start/Stop

AWS Schedule to Start/Stop EC2

by Cloud Watch and Lamda Function

var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var ec2 = new AWS.EC2();
var instances = event.instances.split(/[,;]/);
var params = {
InstanceIds: instances
};
ec2.startInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
throw err;
}else {
context.done(null, 'Started instances '+JSON.stringify(instances));
}
});
};
var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var ec2 = new AWS.EC2();
var instances = event.instances.split(/[,;]/);
var params = {
InstanceIds: instances
};
ec2.stopInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
throw err;
}else {
context.done(null, 'Stopped instances '+JSON.stringify(instances));
}
});
};
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchEventsFullAccess",
"Effect": "Allow",
"Action": "events:*",
"Resource": "*"
},
{
"Sid": "IAMPassRoleForCloudWatchEvents",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:StopInstances",
"ec2:StartInstances"
],
"Resource": [
"*"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment