開発プロジェクトでは、継続的インテグレーション(CI)や継続的デリバリー(CD)のプロセスが重要です。GitHub Actionsはこれらのプロセスを自動化するのに役立ちます。この記事では、GitHub Actionsを使って、ワークフローの実行結果をSlackに通知する方法を説明します。
必要なもの
- GitHubリポジトリ
- Slackワークスペース
- SlackでのIncoming Webhook URL
1: SlackでIncoming Webhookを設定する
- SlackのアプリディレクトリでIncoming Webhooksを検索し、インストールします。
- 新しいWebhookを作成し、通知を受け取りたいチャンネルを選択します。
- Webhook URLをコピーして安全な場所に保存します。
2: GitHubリポジトリにSecretを追加する
- GitHubリポジトリにアクセスします。
- 「Settings」→「Secrets」→「New repository secret」の順に進みます。
- 名前にSLACK_WEBHOOK_URLと入力し、値にSlackのWebhook URLを貼り付けます。
- 「Add secret」をクリックして保存します。
3: GitHub Actionsワークフローを作成する
.github/workflows
ディレクトリに新しいYAMLファイルを作成します。
JOB実行ステータス種類
- success,
- failure,
- cancelled,
- skipped
以下は基本的なワークフローの例です。JOB 失敗
と成功
だけをSlackに通知する
....
jobs:
job-one:
runs-on: ubuntu-latest
.....
job-two:
runs-on: ubuntu-latest
.....
job-three:
runs-on: ubuntu-latest
.....
slack-notification:
runs-on: ubuntu-latest
needs:
- job-one
- job-two
- job-three
# success, failure, cancelled, or skipped
if: always() && (failure() || success())
steps:
- name: "Send Notification to Slack"
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
SLACK_CHANNEL: "your channel name"
SLACK_USERNAME: "GitHub Actions"
SLACK_COLOR: ${{ (needs.job-one.result == 'success' && needs.job-two.result == 'success' && needs.job-three.result == 'success') && 'good' || 'danger' }}
SLACK_MESSAGE: ${{ (needs.job-one.result == 'success' && needs.job-two.result == 'success' && needs.job-three.result == 'success') && '実行成功。' || '<!channel> 実行失敗. ご確認ください。' }}
SLACK_TITLE: "Slack Notification"
SLACK_FOOTER:
"Action URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\n
Branch URL: ${{ github.server_url }}/${{ github.repository }}/tree/${{ github.ref_name }}"
SLACK_ICON: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"