0

I just setup Slack integration of AWS codecommit. Where I received only repository name and branch. Additonally I also want to know who made this commit and commit message.

enter image description here

I did try to setup Input transformer rule. Now It shows two role in Amazon EventBridge.

enter image description here

I have added below input target json. But nothing happens.

{
    "author" : "$.detail.author",
    "repositories" : "$.detail.respositoryNames"
}

This is already ask question here. but there is no proper answer to this question.

Santosh
  • 3,477
  • 5
  • 37
  • 75
  • It's possible that there's no "proper answer" (what would a "proper answer" be?) because there is no way to do it. I'm not saying that there is or is not, just that this is not a good sign. Note that Git itself cannot help you directly as Git does not implement AWS notifications. – torek Aug 29 '22 at 23:14
  • I have manage to achieve what I want with Lambda python function. I created a slack app from slack web and generated a webhook url. I need to paste that webhook url into the lambda function script and set couple of permission to lambda function and voila.. it worked. I will post more details answer in few hours. – Santosh Aug 30 '22 at 02:43

1 Answers1

4

So instead of AWS chat with slack I have managed to make it work with AWS Lambda with python 3.7 script.

You need to create a private/public channel in your slack so that all those commit feed will display there. I have created a private channel. Then create a slack app by follwing below steps.

How to Create a Slack Incoming Webhook URL?

Further in this article, you will require a Slack Incoming Webhook URL to connect your AWS SNS to Slack. Follow the steps below to Create a Slack Incoming Webhook URL from scratch:

Step 1: The first step involved in connecting SNS to Slack requires you to create a Slack App. You can get started by clicking this link – Slack API: Applications.

Step 2: Enable Incoming Webhooks for connecting SNS to Slack. To do so, go to Settings → Incoming Webhooks → Activate Incoming Webhooks. Your page will get refreshed.

Step 3: Create an Incoming Webhook by clicking on Add New Webhook to Workspace.

Step 4: Pick your desired Channel to post your messages from SNS to Slack and click on Authorize.

Step 5: You’ll be redirected to your app settings, where you should now notice a new entry under the Webhook URLs for your Workspace section, with a Webhook URL that looks like this:

https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXX

enter image description here

You need to copy that webhook url and go to AWS Lambda to create a python 3.7 code.

Lambda python 3.7 code

import json
import boto3
import urllib3

codecommit = boto3.client('codecommit')


def lambda_handler(event, context):
    # Log the updated references from the event
    references = {reference['ref'] for reference in event['Records'][0]['codecommit']['references']}
    print("References: " + str(references))
    # Get the repository from the event and show its git clone URL
    repository = event['Records'][0]['eventSourceARN'].split(':')[5]

    try:
        user = event['Records'][0]['userIdentityARN'].split(':')[5].split('/')[1]
        references = event['Records'][0]['codecommit']['references']
        for reference in references:
            commit = reference['commit']
            branch = reference['ref'].split('/')[2]
            commit_resp = codecommit.get_commit(repositoryName=repository, commitId=commit)
            message = commit_resp['commit']['message']
            parent_commit = commit_resp['commit']['parents'][0]
            commit_name = commit_resp['commit']['author']['name']
            diff_resp = codecommit.get_differences(
                repositoryName=repository,
                beforeCommitSpecifier=parent_commit,
                afterCommitSpecifier=commit
            )
            files = ''
            i = 1
            for blobs in diff_resp['differences']:
                files = files + f'\n\t{blobs["afterBlob"]["path"]}'
                i = i+1
                if i > 4:
                    files = files + f'\n\t ...more files'
                    break

            webhook = 'paste your webhook url here.'
            data = {
                "text": f"  <@{commit_name}> (<@{user}>) committed code to {branch} branch of {repository} \nCommit message : {message} \nCommit Id: {commit} \nFiles:{files}"}

            http = urllib3.PoolManager()
            r = http.request("POST", webhook,
                             body=json.dumps(data),
                             headers={"Content-type": "application/json"})

        return 'Success'
    except Exception as e:
        print(e)
        print(
            'Error getting repository {}. Make sure it exists and that your repository is in the same region as this function.'.format(repository))
        raise e

Update your webhook url here.

webhook = 'paste your webhook url here.'

After that add a trigger for Lambda function to codecommit.

enter image description here

Also do add permission for lambda function to access codecommit. After that every commit you will see feed in your channel.

enter image description here

Santosh
  • 3,477
  • 5
  • 37
  • 75
  • Your recommendation is great, however my Lambda got stucked and timed out when trying to gather these details: " commit = reference['commit'] branch = reference['ref'].split('/')[2] commit_resp = codecommit.get_commit(repositoryName=repository, commitId=commit) message = commit_resp['commit']['message'] parent_commit = commit_resp['commit']['parents'][0] commit_name = commit_resp['commit']['author']['name']" – demuxer May 25 '23 at 19:57
  • maybe check logs where it is stuck. Or share the logs report to check. Maybe some property is missing. – Santosh May 26 '23 at 05:48