Created
November 6, 2017 13:34
-
-
Save eddmann/187b551fa76e09ceeac61b0ac569c53e to your computer and use it in GitHub Desktop.
Scheduled Start/Stop of EC2 Instances using Lambda and Serverless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const AWS = require('aws-sdk'); | |
module.exports.start = (event, context, callback) => { | |
const ec2 = new AWS.EC2({ region: event.region }); | |
ec2.startInstances({ InstanceIds: [event.id] }).promise() | |
.then(() => callback(null, `Successfully started ${event.id}`)) | |
.catch(err => callback(err)); | |
}; | |
module.exports.stop = (event, context, callback) => { | |
const ec2 = new AWS.EC2({ region: event.region }); | |
ec2.stopInstances({ InstanceIds: [event.id] }).promise() | |
.then(() => callback(null, `Successfully stopped ${event.id}`)) | |
.catch(err => callback(err)); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
service: start-stop-ec2-instances | |
provider: | |
name: aws | |
runtime: nodejs6.10 | |
stage: prod | |
region: eu-west-1 | |
iamRoleStatements: | |
- Effect: "Allow" | |
Action: | |
- "ec2:StartInstances" | |
- "ec2:StopInstances" | |
Resource: "*" | |
custom: | |
instanceId: %EC2_INSTANCE_ID% | |
start: cron(30 6 * * ? *) | |
stop: cron(30 18 * * ? *) | |
functions: | |
start: | |
handler: handler.start | |
events: | |
- schedule: | |
rate: ${self:custom.start} | |
input: | |
id: ${self:custom.instanceId} | |
region: ${self:provider.region} | |
stop: | |
handler: handler.stop | |
events: | |
- schedule: | |
rate: ${self:custom.stop} | |
input: | |
id: ${self:custom.instanceId} | |
region: ${self:provider.region} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment