Last active
September 12, 2024 17:37
-
-
Save statico/eab2e98f93301639558e866c25238bc5 to your computer and use it in GitHub Desktop.
Simple AWS ECS status update notifications to Slack webhook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Want to know when ECS events happen in Slack? Try this. | |
(1) Create a new Slack app with an incoming webhook, save the webhook URL | |
(2) Create an SNS topic called something like ECSEvents | |
(3) Create a CloudWatch Rule that publishes all ECS events to the topic | |
(4) Create a Node.js Lambda that is triggered by the SNS topic | |
(5) Add a WEBHOOK_URL environment variable to the Lambda with the webhook URL | |
(6) Paste this code into index.js | |
(7) Paste the contents of https://unpkg.com/node-fetch/lib/index.js into fetch.js | |
(8) Deploy and enjoy | |
*/ | |
const fetch = require('./fetch') | |
const RED = '#cd3131' | |
const YELLOW = '#e5e512' | |
const GREEN = '#05bc79' | |
const BLUE = '#2472c8' | |
exports.handler = async(event) => { | |
for (const record of event.Records) { | |
const msg = JSON.parse(record.Sns.Message) | |
console.log(JSON.stringify(msg)) // For debugging | |
const title = msg['detail-type'] | |
const d = msg.detail | |
let color, text, body | |
switch (title) { | |
case "ECS Deployment State Change": | |
color = /COMPLETED/.test(d.eventName) ? GREEN : YELLOW | |
text = d.eventName + '\n' + | |
(msg.resources ? msg.resources.join('\n') : '') | |
break | |
case "ECS Task State Change": | |
color = /DELETED|STOPPED/.test(d.lastStatus) ? RED : | |
/RUNNING/.test(d.lastStatus) ? GREEN : | |
YELLOW | |
text = [ | |
`Cluster: ${d.clusterArn.replace(/^.*\//, '')} / Service: ${d.group.replace(/^.*:/, '')}`, | |
`Task: ${d.taskArn.replace(/^.*\//, '')} (${d.taskDefinitionArn.replace(/^.*\//, '')})`, | |
`Status: ${d.lastStatus} (Desired: ${d.desiredStatus})`, | |
d.stoppedReason && `Stop reason: ${d.stoppedReason}`, | |
].filter(x => x).join('\n') | |
break | |
} | |
if (!text) return | |
body = { attachments: [{ title, text, color }] } | |
console.log(JSON.stringify(body)) // Debugging | |
await fetch(process.env.WEBHOOK_URL, { | |
method: 'post', | |
body: JSON.stringify(body), | |
headers: { 'Content-Type': 'application/json' }, | |
}) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
@statico
I'm trying to setup but I can't find file from step 7