Badges for AWS CodeBuild & CodePipeline with CloudWatch and Lambda

Nov 6, 2017

Most build systems have a built-in method of producing status badges or a
plugin that will create them. With CodeBuild, we can use CloudWatch Events
and a Lambda function to generate a badge when our build succeeds or fails,
upload it to S3 and then display it in our README.

To get started, the following JSON is a shortened example of a CloudWatch event
for a CodeBuild job that failed to run. I’ve removed the “additional-information”
section but we can still see the job that it relates to and also the overall
status.

Stage 2 - Creating the Lambda function

Hit the “Create Function” button and then choose “Author from scratch” on
the right hand side.

Choose a name for your function and in the role selection, select “Create a
custom role”.

In the new window that appears, enter a name for your role and then click
“Show Policy Document” to display the default Lambda function policy. Click
the “Edit” link to the side and enter the following policy. It’s the same
as the default, with an added permission to put badges into our bucket.

Testing it out

Run any of your CodeBuild jobs and check the S3 bucket. If everything has
worked, you’ll see an SVG appear with the project’s name, for example
“website-frontend.svg”. You can link to this in your project’s README or other
documentation.

Happy building!

What about CodePipeline?

If you’re using AWS CodePipeline instead of CodeBuild, you can select the
“Service Name” of “CodePipeline” and the “Event Type” of “CodePipeline Pipeline
Execution State Change” when creating the CloudWatch event. The Lambda function
will work without modification.