Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simplistic lambda function for autoscaling the number of tasks in an ECS service
var aws = require('aws-sdk');
exports.handler = function(event, context) {
var ecsRegion = 'us-east-1';
// Safegaurd against out of control service scaling
var maxCount = {
deathstar: 6
};
var message = JSON.parse(event.Records[0].Sns.Message);
var serviceName;
var clusterName;
for (var dimension in message.Trigger.Dimensions) {
if (message.Trigger.Dimensions[dimension].name == 'ServiceName') {
serviceName = message.Trigger.Dimensions[dimension].value;
}
if (message.Trigger.Dimensions[dimension].name == 'ClusterName'){
clusterName = message.Trigger.Dimensions[dimension].value;
}
}
console.log('The service that triggered this alarm was: ' + serviceName);
console.log('The cluster that triggered this alarm was: ' + clusterName);
var ecs = new aws.ECS({region: ecsRegion});
ecs.describeServices({services:[serviceName], cluster: clusterName}, function(err, data) {
console.log('Finished describing service to fetch current task count');
if (err) {
console.log(err, err.stack);
} else {
var desiredCount = data.services[0].desiredCount;
if (desiredCount < maxCount[serviceName]) {
desiredCount++;
var params = {
service: serviceName,
desiredCount: desiredCount,
cluster: clusterName
};
ecs.updateService(params, function(err, data) {
console.log('Finished updating service task count');
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
context.succeed();
}
});
} else {
console.log('Service count for ' + serviceName + ' is already max on ' + clusterName);
context.fail();
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment