JenkinsのPipelineで呼び出したジョブのビルド番号を取得する

JenkinsのPipelineはとても便利ですが、Groovyで書くスクリプトにはくせがあるような感じがします。今回ハマったのは、呼び出したジョブのビルド番号の取得です。

Jenkinsfile

build jobが戻り値としてRunWrapperクラスを返してくれるそうなので、そこから色んな情報をとれます。しかし、ジョブが途中で失敗したとき、以下のコードではbuild_info.getNumber()NullPointerExceptionになってしまい困っていました。

https://gist.github.com/daipresents/e6e48615ca45c20b776fc42a5d559ed4.js?file=Jenkinsfile-pipeline-1

調べてみると、同じように困っている人がいました。

Get the build number of a failed build in a parallel build in jenkins workflow

propagate: falseを使えばいけるとあったので、調べてみると説明書には以下のようにありました。

If set, then if the downstream build is anything but successful (blue ball), this step fails. If disabled, then this step succeeds even if the downstream build is unstable, failed, etc.; use the result property of the return value as needed.

すごくわかりにくいのですが、僕の認識ではpropagate: falseにすると、ジョブがコケても例外を投げなくなり、かならずbuild_infoが返ってくるみたいです。

ただ、これだと何が起きてもPipelineジョブが成功してしまうので、ジョブ結果の判定をreturn valueを使って自分でやる必要があります。

getResult()SUCCESSFAILURE返すので、スクリプトを書き直すとシンプルになります。

https://gist.github.com/daipresents/e6e48615ca45c20b776fc42a5d559ed4.js?file=Jenkinsfile-pipeline-2

広告