Skip to content

Instantly share code, notes, and snippets.

@eddmann
Created November 3, 2017 14:00
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save eddmann/a9e404eb62056f77610f752606a2e504 to your computer and use it in GitHub Desktop.
Save eddmann/a9e404eb62056f77610f752606a2e504 to your computer and use it in GitHub Desktop.
Scheduled Start/Stop of EC2 Instances using Lambda and CloudWatch Events
// Demonstration video can be found at: https://youtu.be/roAerKVfq-Y
// StopEC2Instance
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
const ec2 = new AWS.EC2({ region: event.instanceRegion });
ec2.stopInstances({ InstanceIds: [event.instanceId] }).promise()
.then(() => callback(null, `Successfully stopped ${event.instanceId}`))
.catch(err => callback(err));
};
// StartEC2Instance
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
const ec2 = new AWS.EC2({ region: event.instanceRegion });
ec2.startInstances({ InstanceIds: [event.instanceId] }).promise()
.then(() => callback(null, `Successfully started ${event.instanceId}`))
.catch(err => callback(err));
};
@niketasinha
Copy link

hello,
can you hep me in how to schedule start/stop for RDS.

@chirapatlathong
Copy link

Hi Edd,

Thanks for this, it's very helpful for my situation.

However I have server that should be start in series, and it should check that the prior server has the service UP before attempting to start itself. i.e. Ping or Test with a simple telnet to specified ports. Would it be possible that Lamda can do something like that ?

Many thanks.

@terryyoung22
Copy link

Very helpful! thanks so much!!!!!!!!!!

@shakka47
Copy link

shakka47 commented Sep 5, 2019

Thanks for help

@shakiralimughal
Copy link

shakiralimughal commented Dec 4, 2019

hello,
can you hep me in how to schedule start/stop for RDS.

Use Serverless RDS type, You can specify the minimum and maximum amount of resources needed.

@BlaShadow
Copy link

For anyone who wants to archive the same behavior with Amazon RDS

Start rds database

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

exports.handler = (event, context, callback) => {
    const rds = new AWS.RDS();

    var params = {
      DBInstanceIdentifier: event.dbIdentifier,
    };

    rds.startDBInstance(params, function(err, data) {
      if (err) {
        console.log(err, err.stack); // an error occurred
      } else {
        console.log('Database started');
      }
    });
}

Stop rds database

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

exports.handler = (event, context, callback) => {
  const rds = new AWS.RDS();

  var params = {
    DBInstanceIdentifier: event.dbIdentifier,
  };

  rds.stopDBInstance(params, function(err, data) {
    if (err) {
      console.log(err, err.stack); // an error occurred
    } else {
      console.log('Database stoped');
    }
});

@ChenLi0830
Copy link

Node 12+ version:

Stop Instance

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

exports.handler = async (event) => {
    const ec2 = new AWS.EC2({ region: event.instanceRegion });
    
    await ec2.stopInstances({ InstanceIds: [event.instanceId] }).promise();
    
    const response = {
        statusCode: 200,
        body: JSON.stringify(`EC2 ${event.instanceId} is stopped successfully`),
    };
    return response;
};

Start Instance


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

exports.handler = async (event) => {
    const ec2 = new AWS.EC2({ region: event.instanceRegion });
    
    await ec2.startInstances({ InstanceIds: [event.instanceId] }).promise();
    
    const response = {
        statusCode: 200,
        body: JSON.stringify(`EC2 ${event.instanceId} is started successfully`),
    };
    return response;
};

@thanksmia
Copy link

thank You! nice tutorial by the way

@tkvenu
Copy link

tkvenu commented Nov 4, 2020

help:

1)EC2 instances - i have mutiple servers and i would like to start/stop using above code...Can anyone help me how to use the code
2) can i merge rds & ec2 stop/start code in one funtion ?

@thanksmia
Copy link

Watch this Video if u want to use it https://www.youtube.com/watch?v=roAerKVfq-Y

@maximus495
Copy link

hello, I have a question, it is possible to start an instance as demand increases??
I have a service in nodejs in a t2micro instance, but I want that when the cpu exceeds a% immediately start another EC2

@marlonklc
Copy link

marlonklc commented Jun 2, 2021

@eddmann thanks a lot, helped me automate my clients' services.

@ChenLi0830 thanks to update script to node 12+

Congrats !

@marlonklc
Copy link

marlonklc commented Jun 2, 2021

help:

1)EC2 instances - i have mutiple servers and i would like to start/stop using above code...Can anyone help me how to use the code
2) can i merge rds & ec2 stop/start code in one funtion ?

yes, with lambda you have the power of code in your hands, so you can do all things that you want. You could add commands to start another EC2 instances for example. Just you need is aws sdk to execute like as CLI commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment