Skip to content

Instantly share code, notes, and snippets.

@statico
Last active October 18, 2023 20:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statico/eab2e98f93301639558e866c25238bc5 to your computer and use it in GitHub Desktop.
Save statico/eab2e98f93301639558e866c25238bc5 to your computer and use it in GitHub Desktop.
Simple AWS ECS status update notifications to Slack webhook
/*
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' },
})
}
};
@zablowoj
Copy link

Hi,
@statico
I'm trying to setup but I can't find file from step 7

@statico
Copy link
Author

statico commented Aug 28, 2023

Ah, you probably need version 2: https://unpkg.com/node-fetch@2.7.0/lib/index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment