How to get the event content in ECS when it is invoked by cloudwatch/eventbridge event?

那年仲夏 提交于 2020-12-12 11:27:05

问题


We can set up event rules to trigger an ECS task, but I don't see if the triggering event is passed to the runing ECS task and in the task how to fetch the content of this event. If a Lambda is triggered, we can get it from the event variable, for example, in Python:

def lambda_handler(event, context):
...

But in ECS I don't see how I can do things similar. Going to the cloudtrail log bucket doesn't sound to be a good way because it has around 5 mins delay for the new log/event to show up, which requires ECS to be waiting and additional logic to talk to S3 and find & read the log. And when the triggering events are frequent, this sounds hard to handle.


回答1:


One way to handle this is to set two targets In the Cloud watch rule.

  • One target will launch the ECS task
  • One target will push same event to SQS

So the SQS will contain info like

{
  "version": "0",
  "id": "89d1a02d-5ec7-412e-82f5-13505f849b41",
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "account": "123456789012",
  "time": "2016-12-30T18:44:49Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:events:us-east-1:123456789012:rule/SampleRule"
  ],
  "detail": {}
}

So when the ECS TASK up, it will be able to read event from the SQS.

For example in Docker entrypoint

#!/bin/sh
echo "Starting container"
echo "Process SQS event"
node process_schdule_event.sj


#or if you need process at run time
schdule_event=$(aws sqs receive-message --queue-url https://sqs.us-west-2.amazonaws.com/123456789/demo --attribute-names All --message-attribute-names All --max-number-of-messages 1)
echo "Schdule Event: ${schdule_event}"


# one process done, start the main process of the container
exec "$@"



回答2:


After further investigation, I finally worked out another solution that is to use S3 to invoke Lambda and then in that Lambda I use ECS SDK (boto3, I use Python) to run my ECS task. By this way I can easily pass the event content to ECS and it is nearly real-time.

But I still give credit to @Adiii because his solution also works.



来源:https://stackoverflow.com/questions/62807320/how-to-get-the-event-content-in-ecs-when-it-is-invoked-by-cloudwatch-eventbridge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!