Skip to content

Instantly share code, notes, and snippets.

@gregsgit
Last active December 4, 2021 05:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregsgit/5c466915942ddeb16a445863b1abc608 to your computer and use it in GitHub Desktop.
Save gregsgit/5c466915942ddeb16a445863b1abc608 to your computer and use it in GitHub Desktop.
AWS Lambda triggered by pushes/commits, constructs simple message and then triggers a SNS topic

Follow the steps in: http://docs.aws.amazon.com/codecommit/latest/userguide/how-to-notify-lambda.html

Below is my summary of what you need to do.

create SNS Topic

  • Visit AWS SNS control panel > Topics > Create topic, name = "commits" or something
  • Create Subscription to topic > email

create an IAM Role

  • Visit IAM control panel > Roles > Create Role
  • Service role: Lambda
  • Add AWSCodeCommitFullAccess policy
  • Add AmazonSNSFullAccess policy

create Lambda Function

  • Visit AWS Lambda control panel > Dashboard

  • Create Function > blueprint = Author from scratch

  • Configure triggers dialogue: click on dashed box, choose CodeCommit, make up a trigger name

  • Configure function dialogue: name something like CodeCommitLambdaFunction, Runtime = Python 2.7

  • Existing role: service-role/CodeCommitLambdaRole

  • paste code from this gist, CodeCommitLambdaFunction_allEvents.py

  • uncomment print of "Received event"

  • Save

  • Commit and push to repo. The Lambda function should get triggered.

  • Go to the Lambda function you created, Monitoring tab, View Logs in CloudWatch, choose event, view in plain text.

  • Grab the text of the incoming event in order to create a test input for your function.

  • Back to Code tab

  • Actions > Configure Test Event

  • paste in '{ "Records" : [ ... ] }' you copied from logs. Save and Test.

# ARN - arn:aws:lambda:us-east-2:750303481583:function:DoverCodeCommitLambdaFunction_allEvents
import json
import boto3
from datetime import datetime as dt
from string import split
codecommit = boto3.client('codecommit')
sns = boto3.client('sns')
doverCommits_topicARN = 'arn:aws:sns:us-east-2:750303481583:DoverCommits'
def lambda_handler(event, context):
#Log the updated references from the event
references = event['Records'][0]['codecommit']['references']
print("References: " + str(references))
repo = event['Records'][0]['eventSourceARN'].split(':')[5]
msg = ""
response = ""
primary_author = ""
for record in references:
commit = record['commit']
ref = record['ref']
# get commit info
try:
response = codecommit.get_commit(commitId=commit, repositoryName=repo)
except Exception as e:
print(e)
print("Error getting commit {}.".format(commit))
raise e
print("get_commit response for commit {} and repo {}:\n\t{}".format(
commit, repo, str(response)))
c = response['commit']
author = c['author']['name']
primary_author = author
authorDate = dt.fromtimestamp(int(split(c['author']['date'])[0]))
committer = c['committer']['name']
committerDate = dt.fromtimestamp(int(split(c['committer']['date'])[0]))
msg += "Commit {}: \n".format(commit)
msg += "Author: {} <{}>. Date: {}\n".format(
c['author']['name'],
c['author']['email'],
dt.isoformat(authorDate))
if author != committer:
msg += "\tCommitter: {} <{}>. Date: {}\n".format(
c['committer']['name'],
c['committer']['email'],
dt.isoformat(committerDate))
msg += "Ref: {}\n".format(ref)
msg += "\n{}\n".format(c['message'])
# get files info
firstParent = c['parents'][0]
try:
response = codecommit.get_differences(
repositoryName=repo,
beforeCommitSpecifier = firstParent,
afterCommitSpecifier = commit)
print("get_differences response = {}".format(json.dumps(response)))
except Exception as e:
print(e)
print("Error doing get_differences")
raise e
msg += "Files:\n"
for diff in response['differences']:
if 'beforeBlob' in diff:
msg += "\t {}".format(
diff['beforeBlob']['path'])
elif 'afterBlob' in diff:
msg += "\t {}".format(
diff['afterBlob']['path'])
msg += " ({})\n".format(
diff['changeType'])
# end of for commit in commits loop
print("publishing message: {}\n".format(msg))
subj = "{} :: {}".format(repo, author)
try:
response = sns.publish(Message=msg,
TopicArn=doverCommits_topicARN,
Subject=subj)
except Exception as e:
print(e)
print("Error doing sns.publish")
raise e
print("publish response: {}".format(json.dumps(response)))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment