Start/Stop ECS Fargate Tasks using Lambda & CloudWatch Events Rules

Peter Eskandar
2 min readJan 8, 2021

Hi all,

I’ve created a simple Lambda function to be able to Start/Stop ECS Service tasks for a specific Cluster.

This Lambda function will be integrated with two CloudWatch Events Rules, a one to start tasks at 10:00 am and another one to stop all task at midnight.

The Lambda code is as following :

const aws = require('aws-sdk');exports.handler = (event, context) => {
// stop all taks
var ecsRegion = 'eu-west-3';
if(event.status == 'stop'){
var params = {
cluster: process.env.ECS_CLUSTER,
service: process.env.ECS_SERVICE_NAME,
desiredCount: 0
};
}
else{
// otherwise : start one task
var params = {
cluster: process.env.ECS_CLUSTER,
service: process.env.ECS_SERVICE_NAME,
desiredCount: 1
};
}
var ecs = new aws.ECS({region: ecsRegion});
ecs.updateService(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
context.succeed();
}
});
};

ECS_CLUSTER and ECS_SERVICE_NAME are two environment variables which are referring to the ECS Cluster and Service names, while status is a variable that should be passed form the CloudWatch Events rule to define whether to start or to stop the tasks using the desiredCount parameter.

Here is how to configure the CloudWatch Events rule:

  • remember to pass the status to the Lambda function : {“status”: “start or stop”}
CloudWatch Events Rule Configuration

To be able to use the Lambda function with different ECS Clusters and Services, instead of setting ECS_CLUSTER and ECS_SERVICE_NAME as environment variables, you can pass both of them from the CloudWatch Evnets rule together with the status as following :

{“status”: “start”, “ECS_CLUSTER”: “demoFargate”, “ECS_SERVICE_NAME”: “demoService”}

modify the Lambda function as shown below :

  • instead of using process.env, we are going to use event
const aws = require('aws-sdk');exports.handler = (event, context) => {
// stop all taks
var ecsRegion = 'eu-west-3';
if(event.status == 'stop'){
var params = {
cluster: event.ECS_CLUSTER,
service: event.ECS_SERVICE_NAME,
desiredCount: 0
};
}
else{
// otherwise : start one task
var params = {
cluster: event.ECS_CLUSTER,
service: event.ECS_SERVICE_NAME,
desiredCount: 1
};
}
var ecs = new aws.ECS({region: ecsRegion});
ecs.updateService(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
context.succeed();
}
});
};

finally, we need to add an IAM policy to enable the Lambda function to update the ECS service, so add the following inline policy to the IAM role attached to your Lambda function

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ecs:UpdateService",
"Resource": "*"
}
]
}

hope it helps

Thanks

--

--