Implementing a Lambda Function to Process CodeCommit Events

Lab Steps

lock
Logging in to the Amazon Web Services Console
lock
Creating a New CodeCommit Repository
lock
Creating an SNS Topic and a Subscription
lock
Implementing a Lambda Function to Process CodeCommit Events
lock
Connecting to the Virtual Machine using EC2 Instance Connect
lock
Testing the CodeCommit Trigger
Need help? Contact our support team

Here you can find the instructions for this specific Lab Step.

If you are ready for a real environment experience please start the Lab. Keep in mind that you'll need to start from the first step.

Introduction

AWS Lambda is a serverless, event-driven compute platform. When using Lambda, you don't have to set up or manage servers, and you only pay for the compute resources you use when your code is executed.

In this lab step, you will implement a Lambda function that processes CodeCommit push events and notifies you by email.

 

Instructions

1. In the AWS Management Console search bar, enter Lambda, and click the Lambda result under Services:

alt

You will see the Functions list page.

 

2. Click Create function:

alt

 

3. Ensure Autor from scratch is selected:

alt

 

4. Under Basic information, in the Function name textbox, enter lab-function:

alt

 

5. In the Runtime drop-down, select Python 3.8.

 

6. Click Change default execution role.

 

7. Select Use an existing role:

alt

 

8. In the Existing role drop-down, select lambda_sns_execution:

alt

This is an IAM role that has been pre-created for this lab.

 

9. Click Create function:

alt

Your browser will load a page where you can see details of your function, and edit and configure the function.

 

10. Scroll down to the Code source section, and double click the lambda_function.py file to open it.

 

11. In the code editor, copy and paste the following code, replacing the existing contents:

Copy code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import boto3

account_id = boto3.client('sts').get_caller_identity().get('Account')
codecommit = boto3.client('codecommit')
sns = boto3.resource('sns')
topic_arn = "arn:aws:sns:us-west-2:%s:lab-topic" % account_id
topic = sns.Topic(topic_arn)

REPO_LINK = "https://console.aws.amazon.com/codecommit/home?region=%s#/repository/%s"

def lambda_handler(event, context):
    print("Processing %s record(s)" % len(event['Records']))
    messages, regions = process_records(event['Records'])
    print("Sending %s notification(s)" % len(messages))
    send_notifications(messages, regions)
    return True

def process_records(records):
    messages = {}
    regions = {}

    for record in records:
        # extract record info
        repo_name = record['eventSourceARN'].split(':')[-1]

        regions[repo_name] = record['awsRegion']
        if repo_name not in messages:
            messages[repo_name] = {}

        for ref in record['codecommit']['references']:
            # extract commit info
            commit_id = ref['commit']
            branch = ref['ref'].split('/')[-1]

            # fetch commit data
            data = codecommit.get_commit(
                repositoryName=repo_name,
                commitId=commit_id,
            )

            message = data['commit']['message']

            if branch not in messages[repo_name]:
                messages[repo_name][branch] = []

            # store (commit_id, message) tuple
            messages[repo_name][branch].append((commit_id, message.strip()))

    return messages, regions

def send_notifications(messages, regions):

    for repo_name in messages:
        repo_url = REPO_LINK % (regions[repo_name], repo_name)
        email_text = "%s repository has had new commits added.\n\n" % repo_name
        email_text += "Repository URL: %s\n\n" % repo_url
        for branch in messages[repo_name]:
            email_text += "----------------------------------------\n"
            email_text += "Branch %s\n\n" % branch
            for commit_id, msg in messages[repo_name][branch]:
                email_text += ' - %s: "%s"\n' % (commit_id, msg)

        topic.publish(
            Message=email_text,
            Subject='AWS CodeCommit - %s' % repo_name,
        )

The code is organized into three Python functions:

  • lambda_handler: The main Lambda logic that will take care of logging and invoking the other functions
  • process_records: Extracts the commit Id and message data for each commit using the CodeCommit API
  • send_notifications: Publishes a new SNS notification for each repository, building a plain-text body

 

12. To deploy your function, at the top of the Code source section, click Deploy.

 

13. Scroll up to the Function overview section and click Add trigger:

alt

A trigger in AWS Lambda is a way of invoking your function. Possible types of triggers that can be configured include:

  • Resources in Lambda
  • Other resources in AWS
  • Schedules

 

14. In the search box, enter CodeCommit and click the CodeCommit result:

alt

The form will expand and you will see more fields to be entered.

 

15. Enter or select the following values in the form, leaving other fields at default if not specified:

  • Repository namelab-repository
  • Trigger namelab-notification
  • EventsPush to existing branch
  • Branch namesAll branches

alt

 

16. Click the X for All repository events:

alt

This leaves Push to existing branch as the only event type that will trigger notifications.

 

17. To add your trigger, click Add:

alt

You will see a notification that your trigger has been created:

alt

 

Summary

In this lab step, you created a Lambda function, added an implementation in Python that processes events from AWS CodeCommit, and, you added a trigger to your Lambda function.

Validation checks
1Checks
Created Lambda Function

Check if the AWS Lambda function has been created

AWS Lambda

Learning Pathnavigation