valid,invalid

関心を持てる事柄について

GitHub Actionsで特定のbranchでのworkflow失敗のみ通知する

GitHub ActionsでCI/CDを組んでいるとき、特定のbranchのみ失敗を通知させたいことがある。たとえば「develop / main branchだけworkflow上でのテストの失敗を通知したい」というようなケース。

結論

jobs.<job_id>.ifでその通りに条件を指定すればよい。

failure()失敗時、かつcontains('refs/heads/develop refs/heads/main', github.ref)

rtCamp/action-slack-notifyを使っているが何でもよい。Slack関連のactions、100個ぐらい乱立している)

# .github/workflows/failure_notification_example.yml
name: Failure notification
on:
  push:
jobs:
  job:
    runs-on: ubuntu-18.04
    steps:
      - name: Run command
        run: |
          foobar # わざと失敗させている
      - name: Notify
        uses: rtCamp/action-slack-notify@master
        if: ${{ failure() && contains('refs/heads/develop refs/heads/main', github.ref) }}
        env:
          SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
          SLACK_COLOR: '#A30100'
          SLACK_TITLE: '"事故"る奴は…"不運-ハードラック-"と”踊-ダンス-"っちまったんだよ…'
          SLACK_MESSAGE: 'See ${{ github.event.repository.url }}/actions/runs/${{ github.run_id }}'
          SLACK_FOOTER: ''
          MSG_MINIMAL: true

f:id:ohbarye:20201103001250p:plain
実行例

これで特定branchでのworkflow失敗に気付くことができる。

説明

GitHub Actionsのstep単位での実行をconditionalに制御するにはjobs.<job_id>.ifを使う。

まず、Job status check functionsで成否に基づく分岐が可能。

jobs:
  job:
    steps:
      - name: Anything
         run: what you want
      - name: conditional step
        if: failure() # 失敗時のみ
#       if: success()   成功時のみ
#       if: always()    常に

また、${{ <expression> }}のexpressionで参照可能なcontextを使い、任意の条件で絞り込める。

branchによる絞り込みであれば

github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main'

でもいいし

contains('
  refs/heads/develop
  refs/heads/main
', github.ref)

でもいい。

その他、syntax, expressionに関するドキュメントを見ればifの条件だけでなくmessageに埋め込める便利情報がたくさんある。