3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JenkinsfileのslackSendの引数を、groovyのJsonBuilderを利用して簡潔に表現する

Posted at

JenkinsfileのslackSend内でattachmentsを指定する際にgroovyのJsonBuilderを利用すると見やすく書けるのですが、groovyを直接使うのに少し手間取ったのでメモしておきます。

実行環境

Jenkins 2.154
Pipeline Plugin 2.6

Pipelineジョブのセットアップやslackとの連携はすでに完了しているものとします。

ビルド結果のSlack通知(attachments指定付き)

slackSend: attachments指定が必要な場合があり、指定するパラメータが多いのでBuilderを使うと便利です。

Jenkinsfile
# !groovy
import groovy.json.JsonBuilder

def attachmentPayload = [[
    fallback: "execution #${env.BUILD_NUMBER}",
    color: "#2eb886",
    pretext: "hogehoge",
    text: "fugafuga #${env.BUILD_NUMBER}",
]]

pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                echo 'test stage'
            }
        }
    }
    post {
        always {
            echo 'TEST DONE'
            script {// ここだけscripted pipeline のsyntaxを適用する
                slackSend(channel: '#targetchannel', color: "#2eb886", attachments: new JsonBuilder(attachmentPayload).toString())
            }
        }
    }
}

Groovyコードブロックの実行を許可する

上記のJenkinsfileを実行するとエラーになります。
new groovy.json.JsonBuilder を実行するためにはホワイトリストに登録してあげなければなりません。
Administrators can ~ を押下するか、「Jenkinsの管理」->「In-process Script Approval」から登録します。

スクリーンショット 2018-12-08 21.34.06.png
図: ビルド実行ログ

スクリーンショット 2018-12-08 21.13.53.png
図: 実行を許可する処理を登録する画面
スクリーンショット 2018-12-08 21.14.08.png
図: 実行を許可する処理を登録したあとの画面

実行結果

投稿できました! :tada:
スクリーンショット 2018-12-08 21.19.33.png

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?