iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😊

Sending Slack Notifications for Step Functions ECS Task Failures

に公開
2024/10/25

I use ECS Tasks as an environment for running cron jobs and one-shot jobs.
In doing so, wrapping them in Step Functions is a common use case because it's a hassle to think about retries, timeouts, and concurrency control.
And when Step Functions fails and an error occurs, I want to notify Slack.
I think this is also a common requirement.
However, I strongly want to avoid the tedious task of issuing a Slack bot token and creating a Lambda just for this!
With that determination, I set up notifications via SNS + AWS Chatbot.
I will use Terraform.

Step Functions

The ECS task URL varies depending on the ECS cluster name.
The following is an example when an ECS cluster named sample is set up in ap-northeast-1.

locals {
  ecs_task_url       = "https://ap-northeast-1.console.aws.amazon.com/ecs/v2/clusters/sample/tasks/"
}

resource "aws_sfn_state_machine" "sample" {
  definition = jsonencode(
    {
      StartAt = "RunTask"
      States = {
        RunTask = {
          Type     = "Task"
          Resource = "arn:aws:states:::ecs:runTask.sync"
          Parameters = {
            LaunchType     = "FARGATE"
            Cluster        = aws_ecs_cluster.sample.arn
            TaskDefinition = replace(aws_ecs_task_definition.sample.arn, "/:\\d+$/", "")
            Overrides = {
              ContainerOverrides = [
                {
                  Name        = "sample"
                  "Command.$" = "$.command"
                }
              ]
            }
            NetworkConfiguration = {
              AwsvpcConfiguration = {
                AssignPublicIp = "ENABLED"
                SecurityGroups = [aws_security_group.sample.id]
                Subnets        = [aws_subnet.sample.id]
              }
            }
          }
          End = true
          Catch = [
            {
              ErrorEquals = [
                "States.ALL"
              ]
              Next = "ModifyOutput1"
            }
          ]
        }
        ModifyOutput1 = {
          Type = "Pass"
          Parameters = {
            "Cause.$" = "States.StringToJson($.Cause)"
          }
          Next = "ModifyOutput2"
        }
        ModifyOutput2 = {
          Type = "Pass"
          Parameters = {
            "Cause.$" = "States.StringSplit($.Cause.TaskArn, '/')"
          }
          Next = "ModifyOutput3"
        }
        ModifyOutput3 = {
          Type = "Pass"
          Parameters = {
            "Cause.$" = "States.Format('see ${local.ecs_task_url}{}/logs?region=ap-northeast-1', $.Cause[2])"
          }
          Next = "SNSPublish"
        }
        SNSPublish = {
          Type     = "Task"
          Resource = "arn:aws:states:::sns:publish"
          Parameters = {
            TopicArn = aws_sns_topic.sample.arn
            Message = {
              version = "1.0"
              source  = "custom"
              content = {
                "description.$" = "$.Cause"
                title           = "error has occurred"
                textType        = "client-markdown"
              }
            }
          }
          Next = "Fail"
        }
        Fail = {
          Type : "Fail"
        }
      }
    }
  )
  name     = "sample"
  role_arn = aws_iam_role.sample.arn
}

For explanation purposes, Retry and Timeout are not configured.
If RunTask fails, it catches everything and triggers AWS Chatbot via SNS to notify Slack.

The output when RunTask fails is in the following format.
Since I want to extract the ECS task ID from this, I'll use Step Functions intrinsic functions.

{
  "name": "RunTask",
  "output": "{\"Error\":\"States.TaskFailed\",\"Cause\":\"{\\\"Attachments\\\":[{\\\"Details\\\":[{\\\"Name\\\":\\\"subnetId\\\",\\\"Value\\\":\\\"subnet-00000000000000000\\\"},{\\\"Name\\\":\\\"networkInterfaceId\\\",\\\"Value\\\":\\\"eni-00000000000000000\\\"},{\\\"Name\\\":\\\"macAddress\\\",\\\"Value\\\":\\\"0a:0a:0a:0a:0a:0a\\\"},{\\\"Name\\\":\\\"privateIPv4Address\\\",\\\"Value\\\":\\\"10.0.0.1\\\"}],\\\"Id\\\":\\\"7975e065-b8b9-477d-b7f2-4ececfa1a5e3\\\",\\\"Status\\\":\\\"DELETED\\\",\\\"Type\\\":\\\"eni\\\"}],\\\"Attributes\\\":[{\\\"Name\\\":\\\"ecs.cpu-architecture\\\",\\\"Value\\\":\\\"arm64\\\"}],\\\"AvailabilityZone\\\":\\\"ap-northeast-1c\\\",\\\"ClusterArn\\\":\\\"arn:aws:ecs:ap-northeast-1:000000000000:cluster/sample\\\",\\\"Connectivity\\\":\\\"CONNECTED\\\",\\\"ConnectivityAt\\\":1715151108682,\\\"Containers\\\":[{\\\"ContainerArn\\\":\\\"arn:aws:ecs:ap-northeast-1:000000000000:container/sample/7446f4e4ff8441eabc8919fe51d8cac5/f5d4dacc-0c3f-43b5-a12d-3b6faf9b0ce5\\\",\\\"Cpu\\\":\\\"0\\\",\\\"ExitCode\\\":1,\\\"GpuIds\\\":[],\\\"Image\\\":\\\"000000000000.dkr.ecr.ap-northeast-1.amazonaws.com/sample:latest\\\",\\\"ImageDigest\\\":\\\"sha256:478663e9244a6f8c1866ea8e59fdc3e8356e08cebb99e5fcc92b2d8dacf891b8\\\",\\\"LastStatus\\\":\\\"STOPPED\\\",\\\"ManagedAgents\\\":[],\\\"Name\\\":\\\"sample\\\",\\\"NetworkBindings\\\":[],\\\"NetworkInterfaces\\\":[{\\\"AttachmentId\\\":\\\"7975e065-b8b9-477d-b7f2-4ececfa1a5e3\\\",\\\"PrivateIpv4Address\\\":\\\"10.0.0.1\\\"}],\\\"RuntimeId\\\":\\\"7446f4e4ff8441eabc8919fe51d8cac5-3286335836\\\",\\\"TaskArn\\\":\\\"arn:aws:ecs:ap-northeast-1:000000000000:task/sample/7446f4e4ff8441eabc8919fe51d8cac5\\\"}],\\\"Cpu\\\":\\\"256\\\",\\\"CreatedAt\\\":1715151105029,\\\"DesiredStatus\\\":\\\"STOPPED\\\",\\\"EnableExecuteCommand\\\":false,\\\"EphemeralStorage\\\":{\\\"SizeInGiB\\\":20},\\\"ExecutionStoppedAt\\\":1715151119396,\\\"Group\\\":\\\"family:sample\\\",\\\"InferenceAccelerators\\\":[],\\\"LastStatus\\\":\\\"STOPPED\\\",\\\"LaunchType\\\":\\\"FARGATE\\\",\\\"Memory\\\":\\\"512\\\",\\\"Overrides\\\":{\\\"ContainerOverrides\\\":[{\\\"Command\\\":[],\\\"Environment\\\":[],\\\"EnvironmentFiles\\\":[],\\\"Name\\\":\\\"sample\\\",\\\"ResourceRequirements\\\":[]}],\\\"InferenceAcceleratorOverrides\\\":[]},\\\"PlatformVersion\\\":\\\"1.4.0\\\",\\\"PullStartedAt\\\":1715151117893,\\\"PullStoppedAt\\\":1715151119256,\\\"StartedAt\\\":1715151119431,\\\"StartedBy\\\":\\\"AWS Step Functions\\\",\\\"StopCode\\\":\\\"EssentialContainerExited\\\",\\\"StoppedAt\\\":1715151144686,\\\"StoppedReason\\\":\\\"Essential container in task exited\\\",\\\"StoppingAt\\\":1715151129486,\\\"Tags\\\":[],\\\"TaskArn\\\":\\\"arn:aws:ecs:ap-northeast-1:000000000000:task/sample/7446f4e4ff8441eabc8919fe51d8cac5\\\",\\\"TaskDefinitionArn\\\":\\\"arn:aws:ecs:ap-northeast-1:000000000000:task-definition/sample:6\\\",\\\"Version\\\":5}\"}",
  "outputDetails": {
    "truncated": false
  }
}

Step Functions Intrinsic Functions

It would have been nice if I could have used nested intrinsic functions, but it didn't seem possible. (It fails validation when trying to save in the Step Functions console.) I gave up and decided to perform the conversion across multiple steps.

1. Convert the escaped JSON string into JSON

   ModifyOutput1 = {
       Type = "Pass"
       Parameters = {
           "Cause.$" = "States.StringToJson($.Cause)"
       }
       Next = "ModifyOutput2"
   }

2. Extract TaskArn from JSON and convert it into an array using '/' as a delimiter

   ModifyOutput2 = {
       Type = "Pass"
       Parameters = {
           "Cause.$" = "States.StringSplit($.Cause.TaskArn, '/')"
       }
       Next = "ModifyOutput3"
   }
{
  "Cause": "arn:aws:ecs:ap-northeast-1:000000000000:task/sample/7446f4e4ff8441eabc8919fe51d8cac5"
}

↓

{
  "Cause": ["arn:aws:ecs:ap-northeast-1:000000000000:task", "sample", "7446f4e4ff8441eabc8919fe51d8cac5"]
}

3. Extract the task ID portion from the array and convert it into a URL to display ECS task logs

   ModifyOutput3 = {
       Type = "Pass"
       Parameters = {
           "Cause.$" = "States.Format('see ${local.ecs_task_url}{}/logs?region=ap-northeast-1', $.Cause[2])"
       }
       Next = "SNSPublish"
   }
{
  "Cause": ["arn:aws:ecs:ap-northeast-1:000000000000:task", "sample", "7446f4e4ff8441eabc8919fe51d8cac5"]
}

↓

{
  "Cause": "https://ap-northeast-1.console.aws.amazon.com/ecs/v2/clusters/sample/tasks/7446f4e4ff8441eabc8919fe51d8cac5/logs?region=ap-northeast-1"
}

4. Pass to SNS and format for AWS Chatbot custom notifications

   SNSPublish = {
       Type     = "Task"
       Resource = "arn:aws:states:::sns:publish"
       Parameters = {
           TopicArn = aws_sns_topic.sample.arn
           Message = {
               version = "1.0"
               source  = "custom"
               content = {
                   "description.$" = "$.Cause"
                   title           = "error has occurred"
                   textType        = "client-markdown"
               }
           }
       }
       Next = "Fail"
   }

Summary

I considered sending the CloudWatch Logs URL, but for now, I used the ECS task URL, which seemed easier to implement. As a result, I have successfully set up Slack notifications without the need for a Lambda function.

Discussion