Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run an AWS ECS Task and then run a Lambda function after its ready then finally stop the Task?

I am new to AWS. I have a Lambda function which I want to run daily at 4:00 AM GMT. The Lambda function is dependent on an AWS ECS Container task to be running. Instead of running the AWS ECS Container task to run always (because it costs a lot for me), I want to be able to trigger to run it and then run the Lambda task when its ready and finally when the Lambda function is finished, I want to stop it.

I looked into this and found that I can run a Lambda function using Amazon EventBridge Rules. I know I can use the CRON expression, 0 4 * * ? *, to run it at 4:00 AM everyday. However, I am not sure how to first run the ECS Container task first and also how to stop the task when the Lambda function finishes.

Other info:

The Lambda function has the Node.js environment.

like image 205
user12055579 Avatar asked Sep 19 '25 08:09

user12055579


1 Answers

ECS emits events to EventBridge (EB). You can setup a rule in the EB to capture events of interest and trigger your lambda function as target for the events.

Example EB rule could be:

{
  "source": [
    "aws.ecs"
  ],
  "detail-type": [
    "ECS Task State Change"
  ],
  "detail": {
    "lastStatus": [
      "RUNNING"
    ]
  }
}

Other customization of the rule are possible.

also how to stop the task when the Lambda function finishes.

Your lambda can use AWS SDK for ECS and stop the tasks. The EB event capture will have info which task was started.

You could also orchestrate your lambda and ecs tasks through step functions:

  • Manage Amazon ECS or Fargate Tasks with Step Functions
like image 152
Marcin Avatar answered Sep 22 '25 07:09

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!