DEV Community

Cover image for AWS ECS Task deployment failed alert using Amazon EventBridge — Part 2 (Terraform code)
Akhil Ghatiki for AWS Community Builders

Posted on

AWS ECS Task deployment failed alert using Amazon EventBridge — Part 2 (Terraform code)

Please read Part 1 for more context before you continue with this blog post

The Part 1 talks about event pattern rule to filter events of a task failure. In this blog post, lets take a look at the terraform code for this implementation

Image description

This blog post assumes you are quite familiar with the Terraform and you have some hands on experience with it.

resource "aws_cloudwatch_event_rule" "ecs_task_failure" {
  count   = length(local.ecs_services_list)
  name          = "${local.ecs_services_list[count.index]}-ecs-task-failed"
  description   = "Rule to monitor failures in ecs tasks"
  event_pattern = <<PATTERN
                  {
                    "source": ["aws.ecs"],
                    "detail-type": ["ECS Task State Change"],
                    "detail": {
                      "group": ["service:service-name"],
                      "stoppedReason": [{
                        "anything-but": {
                          "prefix": "Scaling activity initiated by (deployment"
                        }
                      }],
                      "lastStatus": ["STOPPED"]
                    }
                  }
                  PATTERN
  is_enabled    = true
}
Enter fullscreen mode Exit fullscreen mode

The above snippet creates the event rule as per the pattern we discussed in Part 1.

And you can create the target to this event rule as below.

resource "aws_cloudwatch_event_target" "cloudwatch_alarms" {
  arn       = <<your sns arn>>
  target_id = "service-name-ecs-task-failed-event-target"
  rule      = aws_cloudwatch_event_rule.ecs_task_failure.name
  input     = "{\"Subject\":\"ALARM: ECS task failed - service-name\",\"AlarmDescription\":\"ECS task failed\"}"
}
Enter fullscreen mode Exit fullscreen mode

Now, you can have your lambda triggered for the events coming from the SNS and the lambda can alert the teams (any communication medium that you use)

God Speed !!

Latest comments (0)