user12055579
user12055579

Reputation: 762

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.

Upvotes: 4

Views: 3092

Answers (1)

Marcin
Marcin

Reputation: 238957

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:

Upvotes: 4

Related Questions