groovy或pipleline脚本从Jenkins向Slack发送通知

时间:2018-04-23 06:25:16

标签: groovy jenkins-pipeline webhooks slack

我需要使用Webhooks向jenkins发送通知。我很清楚notifier插件,但为此我需要访问Slack,客户端不想提供。他们提供了Webhook url详细信息。任何人都知道如何发布通知(工作名称,链接,运行它的用户,以及错误原因(如果))松弛

1 个答案:

答案 0 :(得分:0)

正如Matt评论的那样,我们使用curl来做到这一点。我们将它放在一个共享库中,并从管道调用它,下面的示例代码。改进的空间,但应该让你去。

import groovy.json.JsonOutput

def sendBuildNotification(sharedVars, String buildStatus = 'STARTED', String slackHeading = 'BUILD') {

    // Build status of null means success.
    buildStatus = buildStatus ?: 'SUCCESS'
    // Default image is normal Jenkins
    image =':jenkins:'
    long epoch = System.currentTimeMillis()/1000

    // Determine Color
    def color
    if (buildStatus == 'STARTED' || buildStatus == 'ABORTED') {
        color = '#D4DADF' // Grey
    } else if (buildStatus == 'SUCCESS') {
        color = '#319b20' // Green
    } else if (buildStatus == 'UNSTABLE' || buildStatus == 'INPUT REQUIRED') {
        color = '#ff8316' // Yellow
    } else {
        color = '#f44242' // Red
        image=':badjenkins:'
    }

    // Create JSON Payload
    def json = JsonOutput.toJson(
        [
            username: "${slackHeading} ${buildStatus}",
            channel: "${insertChannel}",
            icon_emoji: image,
            attachments: [[
                title: "Job: ${env.JOB_NAME}/${env.BUILD_NUMBER}",
                title_link: "${env.BUILD_URL}console",
                fallback: "Jenkins Job Alert - ${buildStatus} - ${env.JOB_NAME}", 
                color: color,
                fields: [[
                    title: "Repository",
                    value: "<${insert SCM Host}/${env.GIT_REPO_NAME}|${env.GIT_REPO_NAME}>",
                    short: true
                ],[
                    title: "Branch",
                    value: "<${insert SCM Host}/${env.GIT_REPO_NAME}/tree/${BRANCH_NAME}|${BRANCH_NAME}>",
                    short: true
                ],[
                    title: "Last Commit",
                    value: "<${insert SCM Host}/${env.GIT_REPO_NAME}/commit/${sharedVars.gitCommit}|${sharedVars.gitCommit}>",
                    short: false
                ]],
                footer: "<@${env.BUILD_USER_ID}>",
                ts: epoch,
                mrkdwn_in: ["footer", "title"],
            ]]
        ]
    )

    try {
        // Post to Slack
        sh "curl -X POST -H 'Content-type: application/json' --data '${json}' ${slackURL} --max-time 5"
    } catch (err) {
        echo "${err} Slack notify failed, moving on"
    }
}