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

4

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.


 terraform
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 !!

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Create a simple OTP system with AWS Serverless cover image

Create a simple OTP system with AWS Serverless

Implement a One Time Password (OTP) system with AWS Serverless services including Lambda, API Gateway, DynamoDB, Simple Email Service (SES), and Amplify Web Hosting using VueJS for the frontend.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay