Search code examples
python-3.xamazon-web-servicesboto3amazon-ecsaws-event-bridge

How to pass containerOverrides to an ECS task when triggering as a target from eventbridge rule?


I want to write a python code that uses boto3 to assign targets to an eventbridge rule. The target should be an ECS task. Also when the eventbridge rule runs/triggers the ecs task it should override the value of an environment variable named game_id.

What I have tried is to provide the override information in the input

  • the function I am using to assign target is put_targets on a boto3 (events) client
  • Inside the array of targets we have to provide in the argument for Targets I have an element that defines the ecs_task's trigger config
  • Inside this element I have keys like Id, Arn, Input, RoleArn, EcsParameters
  • In the Input key I am providing the json.dumps of a dictionary that looks like:
{
  "containerOverrides": {
    "name": container_name,
    "environment": [
      {
        "name": "game_id",
        "value": game_id
      }
    ]
  }
}
  • Inside the `EcsParameters I am providing a dictionary that looks like (some of the values are variables defined in my environment:
{
  "TaskDefinitionArn": task_definition_arn,
  "TaskCount": 1,
  "LaunchType": "FARGATE",
  "NetworkConfiguration": {
    "awsvpcConfiguration": {
      "Subnets": ECS_NETWORK_SUBNETS,
      "AssignPublicIp": "ENABLED",
      "SecurityGroups": ECS_SECURITY_GROUP
      }
    }
}

The put_targets function executes correctly and I am able to see the rule having the correct target, but it is not triggering the ECS task, at first I thought it was a problem with the IAM role that the rule had, but that wasn't the case as when I changed the input from what I had given to an empty dict, it ran with no issues.

In a way you could say I have implemented this answer: https://stackoverflow.com/a/77047939/11327022

What could be the issue?

Specifically how do we provide containerOverrides when setting an ECS task as a target to an eventbridge rule using boto3?ecs task input


Solution

  • Yes, as @paolo points out, let's figured out if the rule is actually triggering. You can see that in the monitoring tab of the rule (if it gets triggered). If it triggers, but you don't see your task being started, it could be an issue when invoking the target. To troubleshoot, add a DLQ to the target configuration (ideally set all retry values to 0 so any error is immediately DLQ-ed) and then inspect the SQS queue for the detail.