Skip to content

Instantly share code, notes, and snippets.

@eddmann
Created November 7, 2017 13:32
Show Gist options
  • Save eddmann/d817c30357230ed5f5e5d1c401ff86a3 to your computer and use it in GitHub Desktop.
Save eddmann/d817c30357230ed5f5e5d1c401ff86a3 to your computer and use it in GitHub Desktop.
Scheduled Start/Stop of EC2 Instances using Lambda and Serverless (Extra)
'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));
};
'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) ], []);
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