Restart Your ECS Services Using Lambda

In this blog, we will write a python lambda code which will restart our ECS services.

Please follow the below steps to achieve this.

Step 1: Create IAM policy for an IAM Role.

  • Copy the below policy and paste it in your IAM policy.
 1{
 2    "Version": "2012-10-17",
 3    "Statement": [
 4        {
 5            "Sid": "VisualEditor0",
 6            "Effect": "Allow",
 7            "Action": [
 8                "ecs:UpdateService",
 9                "logs:CreateLogGroup",
10                "logs:CreateLogStream",
11                "logs:PutLogEvents"
12            ],
13            "Resource": "*"
14        }
15    ]
16}

Note: To know how to create a custom IAM policy , Please follow this link

Step 2: Create IAM Role and Attached the above IAM policy.

Note: To know how to create IAM Role, Please follow the this link

Step 3: Create Lambda Function.

To create an Lambda Function, Go to Lambda service from AWS console and create a new Function.

Lambda Console

  • Add Lambda Function name. (You can write any name).
  • In Runtime info, Choose "Python 3.9".
  • In permission, Choose "Use an existing Role" in Execution Role
  • In Existing Role, choose the IAM role which you have create above for this Lambda Function.
  • Click on "Create Function".
  • Go to "Function Code" and Paste the below python code in it.
 1import json
 2import boto3
 3import botocore
 4
 5client = boto3.client("ecs")
 6
 7def lambda_handler(event, context):
 8    # TODO implement
 9    cluster = ['cluster-public']         #Please mention your cluster name. You can add multiple cluster.
10    service = ['ECS-service-Name-1','ECS-service-Name-2']    #Please mention your services name. You can add multiple services.
11    for cluster_name in cluster:
12        for service_name in service:
13            try:
14                client.update_service(
15                        cluster= cluster_name,
16                        service= service_name,
17                        forceNewDeployment=True
18                    )
19                print(service_name +" services has been restarted")
20                print("---------------")
21            except botocore.exceptions.ClientError as e:
22                print("Error occur for "+cluster_name+" cluster and "+service_name+" service. Error-Message: ",e)
23                print("---------------")

Note: It will restart all services which you will mentioned in service_name array, based on cluster_name.

  • Save the Lambda Function and Test the same. So that there should be no error.

Step 4: Create Cloudwatch Scheduler and attached the Lambda Function.

  • To configure the scheduler, Open CloudWatch Service and Click on the Rules menu, present in the Left side of your AWS console.

CloudWatch scheduler

  • Click in Create Rule and Select schedule from the Event Source.

CloudWatch Rule image

  • Select the Cron expression and Enter the Timing:

Here I want to take the restart my ECS services daily at 11:30 GMT Monday to Friday. (5:00 PM IST)

CloudWatch scheduler image

Note: Time in CloudWatch is in GMT. You have to check only to convert IST into GMT. You can use this link to convert the time from IST to GMT.

Also, Use this link to learn more about the CloudWatch cron format.

  • Select the Lambda function in Targets and select your function from the drop-down menu.

CloudWatch target

  • Last, enter the Rule name , the description and check the Enabled state check-box.

CloudWatch Last Step

  • Now Click on Create rule to complete the step.

CloudWatch Create Rule

Note: Please note all service should be in the same region.

Step 5: Shit relaxed, Your Scheduler will restart your service daily at given Timing.

I :heart: AWS! :smile: Enjoy