Created
November 7, 2017 13:32
-
-
Save eddmann/d817c30357230ed5f5e5d1c401ff86a3 to your computer and use it in GitHub Desktop.
Scheduled Start/Stop of EC2 Instances using Lambda and Serverless (Extra)
This file contains hidden or 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.stateChange = (event, context, callback) => { | |
const { state, id, region } = event; | |
const ec2 = new AWS.EC2({ region }); | |
ec2[`${state}Instances`]({ InstanceIds: [id] }).promise() | |
.then(() => callback(null, `Successfully ${state} ${id}`)) | |
.catch(err => callback(err)); | |
}; |
This file contains hidden or 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 instances = [ | |
{ | |
id: 'i-11111111111111', | |
region: 'eu-west-1', | |
start: '30 6 * * ? *', | |
stop: '30 18 * * ? *', | |
}, | |
{ | |
id: 'i-00000000000000', | |
region: 'eu-west-1', | |
start: '30 8 * * ? *', | |
stop: '30 16 * * ? *', | |
}, | |
]; | |
// -- | |
const start = ({id, region, start}) => | |
({ schedule: { rate: `cron(${start})`, input: { state: 'start', id, region } } }); | |
const stop = ({id, region, stop}) => | |
({ schedule: { rate: `cron(${stop})`, input: { state: 'stop', id, region } } }); | |
module.exports.schedule = () => | |
instances.reduce((acc, instance) => [ ...acc, start(instance), stop(instance) ], []); | |
This file contains hidden or 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: "*" | |
functions: | |
stateChange: | |
handler: handler.stateChange | |
events: ${file(./instances.js):schedule} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment