Skip to content

Instantly share code, notes, and snippets.

@alexjeen
Last active July 19, 2019 19:19
Show Gist options
  • Save alexjeen/3d601003af488befed043ec6944090aa to your computer and use it in GitHub Desktop.
Save alexjeen/3d601003af488befed043ec6944090aa to your computer and use it in GitHub Desktop.
Sync ECS task account with EC2 instances in AutoscalingGroup (AWS)
exports.handler = async (event, context, callback) => {
console.log('Starting the process');
var AWS = require('aws-sdk');
// set the service names
var ecsClusterName = "clustername";
var ecsServiceName = "servicename";
var autoScalingGroupName = "autoscalinggroupname";
// determine the current desired count
var ecs = new AWS.ECS({'region': 'eu-west-1'});
var params = {cluster: ecsClusterName, services: [ecsServiceName]};
// run autoscale
ecs.describeServices(params, function(err, data) {
if(!err) {
var currentInstances = data.services[0].desiredCount;
if(currentInstances > 0) {
// describe the autoscaling group, and scale up / in if there is a different service count
var as = new AWS.AutoScaling({'region': 'eu-west-1'});
var params = {AutoScalingGroupNames: [autoScalingGroupName]};
as.describeAutoScalingGroups(params, function(err, data) {
if(!err) {
var instances = data.AutoScalingGroups[0].Instances;
var instancesInService = 0;
for(var i in instances) {
if(instances[i].LifecycleState == 'InService') {
instancesInService++;
}
}
if(instancesInService == currentInstances) {
console.log('Current state is OK');
} else {
// scale up / down
var params = {
cluster: ecsClusterName,
service: ecsServiceName,
desiredCount: instancesInService
};
ecs.updateService(params, function(err, data) {
if (!err) {
console.log('Updated desired count to ' + instancesInService);
} else {
console.log(err);
}
});
}
var response = {
statusCode: 200,
body: JSON.stringify([])
};
context.succeed(response);
} else {
context.fail(err);
}
});
}
} else {
context.fail(err);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment