Skip to content

Instantly share code, notes, and snippets.

@hendrixroa
Created January 18, 2020 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrixroa/3c65ba27dad1e32c571564f650429074 to your computer and use it in GitHub Desktop.
Save hendrixroa/3c65ba27dad1e32c571564f650429074 to your computer and use it in GitHub Desktop.
AWS Lambda function triggered by aws codedeploy to send a notification to slack if a deployment was successful or not
const axios = require('axios');
const AWS = require('aws-sdk');
const FunctionShield = require('@puresec/function-shield');
const ENV = process.env;
const slackInfraAlertBot = 'your slack bot token';
FunctionShield.configure(
{
policy: {
read_write_tmp: 'alert',
create_child_process: 'alert',
outbound_connectivity: 'alert',
read_handler: 'alert'
},
disable_analytics: false,
token: ENV.function_shield_token
});
exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
let severity = 'good';
let message = event.Records[0].Sns.Message;
let messageJSON = {};
const stage = 'yourstage';
try {
messageJSON = JSON.parse(message);
} catch (error) {
console.error(error);
return context.fail(error);
}
let postData = {
channel: `your channel`,
username: 'AWS SNS via Codedeploy',
icon_emoji: '',
mrkdwn: true
};
if (messageJSON.status === 'FAILED') {
severity = 'danger';
postData.icon_emoji = ''
} else if (messageJSON.status === 'STOPPED') {
severity = 'warning';
postData.icon_emoji = '';
}
const link = `https://console.aws.amazon.com/codedeploy/home?region=${messageJSON.region}#/deployments/${messageJSON.deploymentId}`;
const appName = messageJSON.applicationName.split('-')[1].toUpperCase();
const commit = messageJSON.eventTriggerName;
postData.attachments = [
{
color: severity,
author_name: `DEPLOYMENT - ${stage.toUpperCase()}`,
text: `*${appName}*: ${commit} (<${link}|Codedeploy>)`,
mrkdwn_in: ['text'],
}
];
const options = {
method: 'post',
url: 'https://slack.com/api/chat.postMessage',
data: postData,
headers: {
'Authorization': `Bearer ${slackInfraAlertBot}`
}
};
try {
await doRequest(options);
return context.succeed();
} catch (error) {
return context.fail(error);
}
};
async function doRequest(options) {
return await axios(options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment