Slack channel notification for aws CodeDeploy using AWS Lambda and AWS SNS

(0 comments)

Step 1 - Configure Slack

  • Create a new channel to receive SNS notifications if you do not have already.
  • Next, configure Slack Integrations. Typically, this is available at https://your-domin-name-goes-here.slack.com/apps: 
  • Search for Incoming Webhooks in search bar and then click on Add Configuration.
  • Add a new Incoming WebHooks integration by selecting the appropriate Slack channel.
  • After adding the integration, you should be presented with Setup Instructions and your Webhook URL.
  • You’re done configuring Slack!

Step 2 - Create a Lambda function

  • In the AWS console, go to Lambda and create a new Lambda function.
  • In the Lambda function name section, give name and description.
  • In the Lambda function code section, choose the None option for Code template. In the code textbox, paste below code:
  • var https = require('https');
    var util = require('util');

    exports.handler = function(event, context) {
    console.log(JSON.stringify(event, null, 2));
    console.log('From SNS:', event.Records[0].Sns.Message);

    var postData = {
    "channel": "#aws-sns",
    "username": "AWS SNS via Lamda :: DevQa Cloud",
    "text": "*" + event.Records[0].Sns.Subject + "*",
    "icon_emoji": ":aws:"
    };

    var message = event.Records[0].Sns.Message;
    var severity = "good";

    var dangerMessages = [
    " but with errors",
    " to RED",
    "During an aborted deployment",
    "Failed to deploy application",
    "Failed to deploy configuration",
    "has a dependent object",
    "is not authorized to perform",
    "Pending to Degraded",
    "Stack deletion failed",
    "Unsuccessful command execution",
    "You do not have permission",
    "Your quota allows for 0 more running instance"];

    var warningMessages = [
    " aborted operation.",
    " to YELLOW",
    "Adding instance ",
    "Degraded to Info",
    "Deleting SNS topic",
    "is currently running under desired capacity",
    "Ok to Info",
    "Ok to Warning",
    "Pending Initialization",
    "Removed instance ",
    "Rollback of environment"
    ];

    for(var dangerMessagesItem in dangerMessages) {
    if (message.indexOf(dangerMessages[dangerMessagesItem]) != -1) {
    severity = "danger";
    break;
    }
    }

    // Only check for warning messages if necessary
    if (severity == "good") {
    for(var warningMessagesItem in warningMessages) {
    if (message.indexOf(warningMessages[warningMessagesItem]) != -1) {
    severity = "warning";
    break;
    }
    }
    }

    postData.attachments = [
    {
    "color": severity,
    "text": message
    }
    ];

    var options = {
    method: 'POST',
    hostname: 'hooks.slack.com',
    port: 443,
    path: '/services/your-slack-webhook-url-info-goes-here'
    };

    var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    context.done(null);
    });
    });

    req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
    });

    req.write(util.format("%j", postData));
    req.end();
    };
  • Function notes:

    • Be gentle, I know you’re a better Node.js developer than I am.
    • The icon_emoji refers to a custom AWS emoji. Use any of the standard Slack emoji, or roll your own (see References below).
    • Make sure you supply your Webhook URL for the path value
  • For Role, either create a new or choose an existing role. The first time you create a function, choose the option to create the Basic execution role. The next time you do this you will be able to select the existing role, lambda_basic_execution.
  • After creating the Lambda function, you should be taken back to the Lambda Function List screen.
  • To test lambda function, In the Sample event/ Configure Test Event textbox, paste the following sample SNS message:
    • {
      "Records": [
      {
      "EventSource": "aws:sns",
      "EventVersion": "1.0",
      "EventSubscriptionArn": "arn:aws:sns:us-east-1...ElasticBeanstalkNotifications-Environment-foo-app...",
      "Sns": {
      "Type": "Notification",
      "MessageId": "111",
      "TopicArn": "arn:aws:sns:us-east-1...ElasticBeanstalkNotifications-Environment-foo-app",
      "Subject": "AWS Elastic Beanstalk Notification - New application version was deployed to running EC2 instances",
      "Message": "Timestamp: Thu May 07 23:38:22 UTC 2015\nMessage: Lambda Function Test: New application version was deployed to running EC2 instances.\n\nEnvironment: foo-app\nApplication: FooApp\n\nEnvironment URL: http://foo.com\nRequestId: 222\nNotificationProcessId: 333",
      "Timestamp": "2015-05-07T23:39:18.628Z",
      "SignatureVersion": "1",
      "Signature": "hello-sig",
      "SigningCertUrl": "https://sns.us-east-1.amazonaws.com/...",
      "UnsubscribeUrl": "https://sns.us-east-1.amazonaws.com/...",
      "MessageAttributes": {}
      }
      }
      ]
      }
  • Click Test button and you will see the message in your slack channel.

Step 3 - Create a SNS topic and configure it with aws lambda function.

  • Go to AWS SNS --> topics --> Create new Topic.
  • Go to topic detail page --> Create subscription.
  • Protocol = AWS Lambda and select the endpoint of the lambda function created from the dropdown.

Step 4 - Final Step to configure the AWS CodeDeploy Trigger with the AWS SNS Topic

  • Go to AWS CodeDeploy --> Click application name.
  • In application detail --> Create Trigger
  • Add Trigger name, select inwhichever Events you want notification in slack for the deployment status.
  • Select the AWS SNS Topic created in previous step.
  • You are Done !!
Current rating: 5

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required