Skip to content

Instantly share code, notes, and snippets.

@polaskj
Forked from dfetterman/lambda_function-ECS-cloudwatch-slack.py
Last active October 27, 2022 10:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save polaskj/4a2be68bb0a9f2be0942e576473905c8 to your computer and use it in GitHub Desktop.
Save polaskj/4a2be68bb0a9f2be0942e576473905c8 to your computer and use it in GitHub Desktop.
Lambda function that takes ECS Cloudwatch events and sends a notification to Slack
#!/bin/bash
# deploy serverless stack
serverless deploy \
--stage "dev" \
--region "us-east-1" \
--service-name "my-service-name" \
--slack-channel "#slack-alerts-example" \
--webhook-url "https://hooks.slack.com/services/12345/12345/abcdefg" \
--ecs-cluster-arn "arn:aws:ecs:us-east-1:123456:cluster/test-cluster"
# Forked from https://gist.github.com/dfetterman/2f7da2ce751154d4c97a14a378d421ef
from __future__ import print_function
from botocore.vendored import requests
from boto3 import session, client
import json
import os
def lambda_handler(event, context):
if "detail-type" not in event:
raise ValueError("ERROR: event object is not a valid CloudWatch Logs event")
else:
if event["detail-type"] == "ECS Task State Change":
detail = event["detail"]
if detail["lastStatus"] == "STOPPED":
Message=json.dumps(detail)
messagedata = json.loads(Message)
stoppedReason = messagedata['stoppedReason']
exitCode = messagedata['containers'][0]['exitCode']
if stoppedReason != "Task stopped by user" \
and not stoppedReason.startswith("Scaling activity initiated by ") \
and exitCode != 0 :
# Send an error status message.
serviceName = messagedata['containers'][0]['name']
env = os.environ['env']
region = os.environ['region']
taskArn = messagedata['taskArn']
clusterArn = messagedata['clusterArn']
payload = {
'channel': os.environ['slackChannel'],
'attachments': [
{
'title': 'ECS Task failure detected for container',
'fields': [
{
'title': 'Service',
'value': serviceName
},
{
'title': 'Stopped Reason',
'value': stoppedReason,
'short': 'true'
}, {
'title': 'Exit Code',
'value': exitCode,
'short': 'true'
},
{
'title': 'Environment',
'value': env,
'short': 'true'
},
{
'title': 'Region',
'value': region,
'short': 'true'
},
{
'title': 'Task ARN',
'value': taskArn
},
{
'title': 'Cluster ARN',
'value': clusterArn
}
],
'color': '#F35A00'
}
]
}
url = os.environ['webhookUrl']
headers = {"content-type": "application/json" }
response = requests.put(url, data=json.dumps(payload), headers=headers)
# print(json.dumps(messagedata))
print(response.status_code)
print(response.content)
service: ${opt:service-name}-${opt:region}
provider:
name: aws
runtime: python3.6
functions:
lambda:
handler: ecs-slack-alerts.lambda_handler
events:
- cloudwatchEvent:
enabled: true
event:
source:
- "aws.ecs"
detail-type:
- "ECS Task State Change"
detail:
clusterArn:
- ${opt:ecs-cluster-arn}
environment:
slackChannel: ${opt:slack-channel}
webhookUrl: ${opt:webhook-url}
region: ${opt:region}
env: ${opt:stage}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment