【概要】
先に書いた
https://zuntan02.hateblo.jp/entry/2021/04/14/183922
をベースに、CloudWatchEventsによりCodePipelineのステージの挙動(CodePipeline Stage Execution State Change)を拾って
[(CloudWatch Eventsで)CodePipelineの状態変更検知]
→ [Amazon SNS]
→ [AWS Lambda]
→ [Microsoft Teams]
のような通知を作成した。とりあえず届けばいい人向け。
※上記同様HookURLの暗号化のあたりはLambdaの環境変数にそのまま持たせてます
【参考】
https://dev.classmethod.jp/articles/notify-codepipeline-events-to-slack/
例によってほぼそのままです。
【詳細】
1)Lambdaの関数作成
コード
#!/usr/bin/python3.8 import boto3 import json import logging import os from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError logger = logging.getLogger() logger.setLevel(logging.INFO) HOOK_URL = os.environ['HookUrl'] def lambda_handler(event, context): logger.info("Event: " + str(event)) message = json.loads(event['Records'][0]['Sns']['Message']) logger.info("Message: " + str(message)) region = message['region'] pipeline_name = message['detail']['pipeline'] stage_name = message['detail']['stage'] state = message['detail']['state'] teams_message = { 'text': "State %s (Pipeline %s) is now %s :https://%s.console.aws.amazon.com/codepipeline/home?region=%s#/view/%s" % (stage_name, pipeline_name, state, region, region, pipeline_name) } req = Request(HOOK_URL, json.dumps(teams_message).encode('utf-8')) try: response = urlopen(req) response.read() logger.info("Message posted to Teams") except HTTPError as e: logger.error("Request failed: %d %s", e.code, e.reason) except URLError as e: logger.error("Server connection failed: %s", e.reason)
3)CloudWatchEentsルール作成
[CloudWatch]-[CloudWatch Events]
ルールを作成する
イベントパターン
サービス名:CodePipeline
イベントタイプ:CodePipeline Stage Execution State Change
ターゲット:SNSトピック
→2)で作成したSNトピック名
4)テスト
任意のCodePipelineを実行
State Build (Pipeline <pipeline_name>) is now FAILED : https://ap-northeast-1.console.aws.amazon.com/codepipeline/home?region=ap-northeast-1#/view/<pipeline_name>
の様な通知が届く