LoginSignup
0
0

More than 1 year has passed since last update.

CodeCommitのプルリクエストをSlackに通知する

Last updated at Posted at 2021-06-01

構成

image.png

Lambdaを作成

lambdaのコードです。userdict、slackのトークン、slackのチャンネルは各自編集してください。

lambda_function.py
import logging
import pprint
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def SendToSlackMessage(message):
    #tokenとチャンネルIDは各自編集してください
    client = WebClient(token='your_slackbot_token') 
    response=client.chat_postMessage(channel='your_slack_channel', text=message)

def lambda_handler(event, context):

    pprint.pprint(event)

    repositoryname=event["detail"]["repositoryNames"][0]

    #arnとslackに通知したいユーザー名を対応させます。
    userdict={
      "arn:aws:iam::account_id:user/your_username":"shoma",
    }
    requestauthor=event["detail"]["author"]
    authorname=userdict[requestauthor]


    destinationReference=event["detail"]["destinationReference"]
    destinationBranch=destinationReference.split("/")[2]


    sourceReference=event["detail"]["sourceReference"]
    sourceBranch=sourceReference.split("/")[2]

    pullRequestId=event["detail"]["pullRequestId"]
    url="https://ap-northeast-1.console.aws.amazon.com/codesuite/codecommit/repositories/"+repositoryname+"/pull-requests/"+pullRequestId+"/changes?region=ap-northeast-1"

    if event["detail"]["pullRequestStatus"] =="Open":
      if event["detail"]["event"] =="pullRequestCreated":
        message=":clap:"+authorname+"さんがプルリクエストをオープンしました!:clap:"\
        +"\n【Repository】 "+repositoryname\
        +"\n【Branch】 "+sourceBranch+"→"+destinationBranch\
        +"\n"+url
        SendToSlackMessage(message)

slackでのbot作成方法はこちら

CloudWatchEventでルールを作成する

CloudWatchEventで以下のルールを作成します。

設定
イベントパターン
サービス名 CodeCommit
イベントタイプ CodeCommit Pull Request State Change
ARN別任意のリソース
ターゲット Lambda関数

 image.png

完成例

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0