Monitor your AWS CodeBuilds via Lambda and Slack

Written by rgfindley | Published 2017/09/01
Tech Story Tags: aws | codebuild | cloudwatch | lambda | serverless

TLDRvia the TL;DR App

I recently setup AWS CodePipeline and CodeBuild to perform continuous integration and testing. The piece that was missing out of the box was build notifications. I want to know if my build passes or fails, and if it fails what the errors were.

I was able to throw together a quick solution using AWS CloudWatch Events, Lambda, and Slack. Here’s how it works…

CloudWatch Events trigger a Lambda for all CodeBuild phases. The Lambda POST’s a message to a Slack web hook. I get the Slack message… Live is good.

I used CloudFormation to define and deploy the stack.

Lambda Permissions & Function

_## Role that our Lambda will assume to provide access to other AWS resources

_IamRoleLambdaExecution:Type: AWS::IAM::RoleProperties:AssumeRolePolicyDocument:Version: '2012-10-17'Statement: - Effect: AllowPrincipal:Service: - lambda.amazonaws.comAction: - sts:AssumeRolePath: '/'

_## Create a Policy and attach it to our Lambda Role.

_IamPolicyLambdaExecution:Type: AWS::IAM::PolicyDependsOn: IamRoleLambdaExecutionProperties:PolicyName: IamPolicyLambdaExecutionPolicyDocument:Version: '2012-10-17'Statement: - Effect: AllowAction: - logs:*Resource: '*'Roles: - Ref: IamRoleLambdaExecution

## Lambda Function#SlackFunction:Type: AWS::Lambda::FunctionProperties:Handler: slack.handlerTimeout: 5Role:Fn::GetAtt: - IamRoleLambdaExecution- ArnCode:S3Bucket: <your s3 bucket>S3Key: 'slack.js.zip'Runtime: nodejs6.10Environment:Variables:SLACK_HOOK_URL: <your slack url>

Upload the lambda function below to an S3 bucket as a zip file. Replace the bucket path and slack hook url in the CloudFormation snippet above.

CloudWatch Events

_## CloudWatch Event to trigger lambda for build slack notifications.

_BuildEventRule:Type: 'AWS::Events::Rule'Properties:Description: 'BuildEventRule'EventPattern:source: - 'aws.codebuild'detail-type: - 'CodeBuild Build State Change'detail:build-status: - 'IN_PROGRESS'- 'SUCCEEDED'- 'FAILED'- 'STOPPED'State: 'ENABLED'Targets: -Arn: !GetAtt SlackFunction.ArnId: 'BuildRuleLambdaTarget'

## Permission for CloudWatch to invoke our Lambda#PermissionForBuildEventsToInvokeLambda:Type: 'AWS::Lambda::Permission'Properties:FunctionName: !Ref SlackFunctionAction: 'lambda:InvokeFunction'Principal: 'events.amazonaws.com'SourceArn: !GetAtt BuildEventRule.Arn

Now our Lambda will be invoked when CodeBuild changes state.

Lambda Code

That’s it!

If you want to limit your notifications to a specific CodeBuild instance you can add that to the EventPattern using the project-name. For example:

EventPattern:source: - 'aws.codebuild'detail-type: - 'CodeBuild Build State Change'detail:project-name: - '<your CodeBuild name>'build-status: - 'IN_PROGRESS'- 'SUCCEEDED'- 'FAILED'- 'STOPPED'


Published by HackerNoon on 2017/09/01