Skip to content

Instantly share code, notes, and snippets.

@andrewodri
Last active December 1, 2021 21:27
Show Gist options
  • Save andrewodri/d24518bd0afdb168bd7491284462f2da to your computer and use it in GitHub Desktop.
Save andrewodri/d24518bd0afdb168bd7491284462f2da to your computer and use it in GitHub Desktop.
AWS SNS to Slack Lambda Function
const https = require('https')
const url = require('url')
const slackWebhookUrl = process.env.slackWebhookURL
const slackChannel = process.env.slackChannel
const postMessage = message => new Promise((resolve, reject) => {
const data = JSON.stringify(message)
const slackRequest = Object.assign(url.parse(slackWebhookUrl), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data),
}
})
const httpsRequest = https.request(slackRequest, httpsResponse => {
const chunks = []
httpsResponse.setEncoding('utf8')
httpsResponse.on('data', chunk => chunks.push(chunk))
httpsResponse.on('end', () => {
resolve({
data: chunks.join(''),
statusCode: httpsResponse.statusCode,
statusMessage: httpsResponse.statusMessage,
})
})
}).on('error', e => reject(e.message)).end(data)
})
const processEvent = async event => {
const snsMessage = event.Records[0].Sns.Message
try {
const result = await postMessage({
channel: slackChannel,
text: `${snsMessage.AlarmName} state has changed to ${snsMessage.NewStateValue}: ${snsMessage.NewStateReason}`,
})
if (result.statusCode === 200) {
console.log('Slack Webhook Request Succeeded')
}else{
console.log(`Slack Webhook Request Failed: ${result.statusCode} ${result.statusMessage}`)
}
return null
} catch (error) {
console.log(`Slack Webhook Request Failed: ${error}`)
return false
}
}
exports.handler = async (event, context, callback) => {
const isSuccess = await processEvent(event)
callback(isSuccess)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment