はじめに
この記事は以前書いたGitHub ActionsからSlackに通知を飛ばす方法の続きです。久しぶりにこのワークフローをいじる機会があったので備忘録です。 前の記事も併せて御覧ください。
前回までのおさらい
API定義の変更や新規APIの追加によりSwaggerファイルが更新された際に、Slackに通知するワークフローを書いてました。ありがたいお便りを受けて、最終的に次のように実装していました。
name: notify on: pull_request: types: ['closed'] paths: - 'webapi/swagger/**' branches: - main jobs: notify: name: Slack Notification runs-on: ubuntu-latest steps: - name: 'Send Notification' run: | cat "$GITHUB_EVENT_PATH" | jq '{ attachments: [{ pretext: "Swagger が更新されたよ!", color: "good", title: .pull_request.title, title_link: .pull_request.html_url }] }' | curl -H 'Content-Type: application/json' -d @- ${{ secrets.SLACK_WEBHOOK }}
Pull Request イベントのアクションが closed
となったときに走るワークフローとして登録しています。
$GITHUB_EVENT_PATH
で読み取っているファイルには、このGitHub Actionが走ったイベントのペイロードが格納されています。
ここでひとつ問題なのが、Pull Requestイベントの closed
アクションはPull Requestが閉じたときであり、マージされたかどうかは関係ないということです。
とあるPull RequestでSwaggerファイルに変更を入れたけど、何らかの理由でPull Requestをマージせずに閉じちゃった……なんてケースでもSlackにお知らせが飛んでしまいます。
じゃあどうするか?
答えは簡単で、同じPull Requestイベントのペイロードに merged
というマージされたかどうかを表すフィールドがあります。GitHubの公式ドキュメントにも
If the action is closed and the merged key is false, the pull request was closed with unmerged commits. If the action is closed and the merged key is true, the pull request was merged.
とバッチリ明記されてます。というわけでワークフローを次のように書き換えればOKです。
jobs: notify: name: Slack Notification runs-on: ubuntu-latest steps: - name: 'Send Notification' if: github.event.Pull_request.merged run: | cat "$GITHUB_EVENT_PATH" | jq '{ attachments: [{ pretext: "Swagger が更新されたよ!", color: "good", title: .pull_request.title, title_link: .pull_request.html_url }] }' | curl -H 'Content-Type: application/json' -d @- ${{ secrets.SLACK_WEBHOOK }}
merged
は true or false をとるので if 句にそのまま渡すことができます。これでPull RequestがマージされたときだけSlack通知が飛ぶようになりました。
……しかし、ちょっと調べればすぐ行き着きそうな答えに当時なぜ気付かなかったんでしょうね。。
まとめ
以前実装したワークフローを改良し、Pull Requestがマージされたときだけ実行されるようにしました。
みんな、公式ドキュメントはちゃんと読みましょう。お兄さんとの約束だ