🎡

GitHub Actionsからビルド結果をSlackに通知するための手順

2023/01/17に公開

毎回手順がよく分からなくなって手間取るのでメモしておきます✍️

1. ワークフローの設定を書く

name: CI

on: push

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Notify Slack start
        if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/release' }}
        id: slack
        env:
          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
        uses: voxmedia/github-action-slack-notify-build@v1
        with:
          channel: test-notify
          status: STARTING
          color: warning

      # ...

      - name: Notify Slack success
        if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/release') && success() }}
        env:
          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
        uses: voxmedia/github-action-slack-notify-build@v1
        with:
          message_id: ${{ steps.slack.outputs.message_id }}
          channel: test-notify
          status: SUCCESS
          color: good

      - name: Notify Slack failure
        if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/release') && failure() }}
        env:
          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
        uses: voxmedia/github-action-slack-notify-build@v1
        with:
          message_id: ${{ steps.slack.outputs.message_id }}
          channel: test-notify
          status: FAILED
          color: danger

参考:https://github.com/voxmedia/github-action-slack-notify-build

ここでは

  • 通知先のチャンネル名は test-notify とする
  • main release のいずれかのブランチに対する変更のみSlackに通知する
  • Slack APIのBOTトークンは SLACK_BOT_TOKEN というシークレットとして登録する

という内容としてあります。

2. Slackアプリを作成

  1. https://api.slack.com/apps を開く
  2. Create New App をクリック
  3. From scratch を選択
  4. App Name を適当に入力して、インストール対象のワークスペースを選択
    • このとき、App Name/ が含まれていると Hmm, something went wrong. Try Again? というエラーになるっぽい ので要注意
    • / を含んだ名前にしたい場合は、作成後に変更すればOK

3. 作成されたアプリにスコープを設定してBOTトークンを取得

  1. Add features and functionalityBots を開く
  2. First, assign a scope to your bot tokenReview Scopes to Add をクリック
  3. READMEの説明 に従って、chat:write channels:read groups:read の3つのスコープを Bot Token Scopes に追加
  4. そのまま画面上部の OAuth Tokens for Your WorkspaceInstall to Workspace をクリックし、次の画面で 許可する をクリック
  5. インストールが完了するとトークンが表示されるので、これをコピーしておく

4. BOTトークンをGitHubにシークレットとして登録

https://github.com/{owner}/{repo}/settings/secrets/actions/new

にて、コピーしておいたBOTトークンを SLACK_BOT_TOKEN という名前で登録する

5. Slackで目的のチャンネルにアプリを追加

この画面で、当該アプリを 追加 する

以上🎉

GitHubで編集を提案

Discussion