0
0

More than 1 year has passed since last update.

EventBridgeからSlackにメッセージを送る

Last updated at Posted at 2022-07-02

やリたいこと

EventBridgeから👇のフォーマットでSlackに送ると

こんな感じ👇のメッセージが投稿できる
image.png

調べてみた

EventBridgeからSlackにメッセージを送るサンプル(公式)は👇にある

がしかし、うまく動かなかったので、理解しながら作り替えてみた。

とりあえず”動くこと”を確認したいので、トリガーとして1分に一回起動するようにした。

事前準備

  • SlackにHUBOTを入れる
  • HUBOTをチャンネルに参加させる
  • HUBOTからAPIトークンを取得する

※ AWS Secrets Managerも使うことになります

概要

  • 1、EventBridge用のIAMロールを作る
  • 2、"接続"(APIの送信先)を作る
  • 3、APIの送信先を作る
  • 4、イベントルールを作る
←(ここをクリックすると展開) CFnテンプレ全体はこちら
AWSTemplateFormatVersion: 2010-09-09
Description: "EventBridge to Slack"
Parameters:
  HubotAPIToken:
    Type: String
    NoEcho: true
    Description: APIToken from Slack HUBOT. ex.. xoxb-399999-9999999-hogefugahoge
Resources:
  SlackRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - events.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: '/service-role/'
      Policies:
        - PolicyName: eventbridge-api-destinations
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - events:InvokeApiDestination
                Resource: !GetAtt SlackDestination.Arn
  SlackConnection:
    Type: AWS::Events::Connection
    Properties:
      AuthorizationType: API_KEY
      AuthParameters:
        ApiKeyAuthParameters:
          ApiKeyName: Authorization
          ApiKeyValue: !Sub "Bearer ${HubotAPIToken}"
  SlackDestination:
    Type: AWS::Events::ApiDestination
    Properties:
      ConnectionArn: !GetAtt SlackConnection.Arn
      HttpMethod: POST
      InvocationEndpoint: https://slack.com/api/chat.postMessage
      InvocationRateLimitPerSecond: 10
  SlackRule:
    Type: AWS::Events::Rule
    Properties:
      State: DISABLED
      ScheduleExpression: "rate(1 minute)"
      Targets:
        - Id: slack-destination
          Arn: !GetAtt SlackDestination.Arn
          RoleArn: !GetAtt SlackRole.Arn
          InputTransformer:
            InputPathsMap:
              "channel": "$.detail"
            InputTemplate: |
              {
                "channel": "#test",
                "username": "hogehoge",
                "icon_emoji": ":tea:",
                "text":"ホゲホゲText"
              }

詳細

HUBOTからAPIトークンを取得する

image.png

1、EventBridge用のIAMロールを作る

EventBridgeに対して、"events:InvokeApiDestination"の実行権限を渡す
(参考サイトのママ)

  SlackRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - events.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: '/service-role/'
      Policies:
        - PolicyName: eventbridge-api-destinations
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - events:InvokeApiDestination
                Resource: !GetAtt SlackDestination.Arn

2、"接続"(APIの送信先)を作る

パラメータで設定したHUBOT APIトークン文字列の前に "Bearer"をつけたものが、AWS Secrets Managerに登録されます。

※ APIキーは安全に取り扱いください。。
(公式サンプルでは、何から小難しいことをしているので)

  SlackConnection:
    Type: AWS::Events::Connection
    Properties:
      AuthorizationType: API_KEY
      AuthParameters:
        ApiKeyAuthParameters:
          ApiKeyName: Authorization
          ApiKeyValue: !Sub "Bearer ${HubotAPIToken}"

image.png

3、APIの送信先を作る

上記の”接続”を使って、HUBOT指定のURLにPOSTするように設定

  SlackDestination:
    Type: AWS::Events::ApiDestination
    Properties:
      ConnectionArn: !GetAtt SlackConnection.Arn
      HttpMethod: POST
      InvocationEndpoint: https://slack.com/api/chat.postMessage
      InvocationRateLimitPerSecond: 10

image.png

4、イベントルールを作る

このサンプルでは、とりあえずSlackにメッセージ投稿できれば良いので、
1分に一回起動するようにした
あと、初期状態ではルールを無効化しているので、管理コンソールから有効化する

  SlackRule:
    Type: AWS::Events::Rule
    Properties:
      State: DISABLED
      ScheduleExpression: "rate(1 minute)"

image.png

Slackに送信する部分。
入力パラメータをよしなに変換して、”APIの送信先”に送る
(このサンプルではスケジュール起動なので、入力パラメータは無い)

      Targets:
        - Id: slack-destination
          Arn: !GetAtt SlackDestination.Arn
          RoleArn: !GetAtt SlackRole.Arn
          InputTransformer:
            InputPathsMap:
              "channel": "$.detail"
            InputTemplate: |
              {
                "channel": "#test",
                "username": "hogehoge",
                "icon_emoji": ":tea:",
                "text":"ホゲホゲText"
              }

image.png

InputTemplate: の部分を👇のフォーマットで送るって感じで。

このサンプルでは、スケジュールトリガーとしていますが、
トリガーと変換ルールを組み合わせれば、いい感じに仕上がるんじゃないかと

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