Skip to content

Instantly share code, notes, and snippets.

@mindlapse
Created August 19, 2019 01:58
Show Gist options
  • Save mindlapse/66d50a9d50a77a2bd77b9328f9212eb0 to your computer and use it in GitHub Desktop.
Save mindlapse/66d50a9d50a77a2bd77b9328f9212eb0 to your computer and use it in GitHub Desktop.
'use strict';
const AWS = require('aws-sdk');
const TAG = process.env.TAG
const SNS_TOPIC_ARN = process.env.SNS_TOPIC_ARN
const ec2 = new AWS.EC2()
// Used to send a notification to SNS
const sendNotification = async (subject, instanceIds) => {
console.log(await new AWS.SNS().publish({
TopicArn : SNS_TOPIC_ARN,
Subject : subject,
Message : `Instance Ids: ${instanceIds}`
}).promise())
}
// Asks EC2 for a list of instances in the given state and returns their
// instance IDs.
const getSleepyInstances = async (state) => {
const filter = { Filters: [{Name: "tag:" + TAG, Values: ["True"]}] };
const results = await new AWS.EC2().describeInstances(filter).promise();
const ids = [];
(results.Reservations || []).forEach(r => r.Instances.
filter(i => i.State.Name == state).
forEach(i => ids.push(i.InstanceId)))
return ids;
}
// Performs a start or stop instance action on any tagged instances
// in the given state, then publishes a notification to SNS.
const sleepcycle = async (state, message, action) => {
try {
const instanceIds = await getSleepyInstances(state);
if (instanceIds.length > 0) {
await action(instanceIds)
if (SNS_TOPIC_ARN) await sendNotification(message, instanceIds)
}
return {
statusCode: 200,
message,
body: JSON.stringify({ ids: instanceIds }, null, 2),
};
} catch (e) {
console.log(e)
throw e
}
}
// Lambda endpoint for starting instances
module.exports.goodmorning = async () =>
await sleepcycle('stopped', 'Instances waking up',
(async ids => await ec2.startInstances({ InstanceIds: ids }).promise()))
// Lambda endpoint for stopping instances
module.exports.goodnight = async () =>
await sleepcycle('running', 'Instances going to sleep',
(async ids => await ec2.stopInstances({ InstanceIds: ids }).promise()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment