前置き
GitHubActionsにおいて、testジョブ => deployジョブの順 で実行するようなことはよくあると思います
(testじゃなく、buildでもなんでもいいですが。。)
name: ci
on:
push:
branches: [ develop ]
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: test-step#1
run: echo This is test#1.
- name: test-step#2
run: echo This is test#2.
- name: test-step#3
run: echo This is test#3.
deploy:
runs-on: ubuntu-latest
needs: test
steps:
- name: deploy-step#1
run: echo This is deploy#1.
- name: deploy-step#2
run: echo This is deploy#2.
- name: deploy-step#3
run: echo This is deploy#3.
このようなワークフローにおいて、testジョブだけを実行したい、deployジョブだけを実行したいという必要性がでてきた場合にどのようなことができるのかを検証してみたので、メモとして残します。
前提
条件の指定方法はいろいろありますが、今回はpushイベントなどは[skip ci]
キーワードをマージのコミットメッセージで含めることでワークフローの実行をスキップさせて、workflow_dispatchによる手動実行時に条件を追加させる方法を前提に記載します。
testジョブだけを実行する
こっちは、至って簡単です。後続ジョブであるdeployジョブに実行条件を追加します。
name: conditional-job-only-test
on:
push:
branches: [ develop ]
workflow_dispatch:
inputs:
onlytest:
description: "Run only test job. 'true' is skip deploy job."
required: false
default: ""
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: test-step#1
run: echo This is test#1.
- name: test-step#2
run: echo This is test#2.
- name: test-step#3
run: echo This is test#3.
deploy:
runs-on: ubuntu-latest
if: github.event.inputs.onlytest != 'true'
needs: test
steps:
- name: deploy-step#1
run: echo This is deploy#1.
- name: deploy-step#2
run: echo This is deploy#2.
- name: deploy-step#3
run: echo This is deploy#3.
"onlytest"にtrueを入力して実行した結果は以下の通り。
deploy(後続)ジョブだけを実行する
なんとなく想像はしていましたが、先行となるtestジョブの全体をスキップしてしまうと案の定、deployジョブも実行されませんでした。
そこで試しに、testジョブのすべてのステップに条件を書いて見たところ、うまく成功しました!
name: conditional-job-skip-test
on:
workflow_dispatch:
inputs:
skiptest:
description: "Run only deploy job. 'true' is skip test job."
required: false
default: ""
jobs:
test:
runs-on: ubuntu-latest
#if: github.event.inputs.skiptest != 'true'
# => これだとdeployジョブも実行されないのでtest配下の全stepに条件を記載
steps:
- name: test-step#1
if: github.event.inputs.skiptest != 'true'
run: echo This is test#1.
- name: test-step#2
if: github.event.inputs.skiptest != 'true'
run: echo This is test#2.
- name: test-step#3
if: github.event.inputs.skiptest != 'true'
run: echo This is test#3.
deploy:
runs-on: ubuntu-latest
needs: test
steps:
- name: deploy-step#1
run: echo This is deploy#1.
- name: deploy-step#2
run: echo This is deploy#2.
- name: deploy-step#3
run: echo This is deploy#3.
所感
上記の方法は書くのがめんどくさいし、条件のつけ漏れがあると動いてしまうというリスクもあるのであまり良い方法とは思えません。
もう一つ考えたのは、testジョブを失敗させて、deployジョブに if: alwasy()
で必ず実行させるパターンです。
ただ、これも結果がエラーとして残る点だったり、testジョブを実行して失敗した場合にはdeployジョブが動かないようにする条件を記載する必要があったりとあんまり良い方法とは思えません。
ということで、needsに条件が書けるようになったらうれしいなぁ。。
と書いてみても思いましたが、こんなケースはイレギュラーなのでどうしても必要になったら、deploy(後続)ジョブだけ実行するワークフローをコピペで作ればよいような気もしてきました。