2016-08-25 172 views
18

我在詹金斯v2.19中有一個管道groovy腳本。另外我還有一個
「Slack Notification Plugin」v2.0.1和「Groovy Postbuild Plugin」。Jenkins管道構建失敗後如何發送Slack通知?

我已經成功發送消息「開始構建」和「構建完成」(如果有的話)。

當某些構建步驟失敗時 - 如何向Slack通道發送消息「構建失敗」?

+0

在我看來,Slack插件已經有一個「通知失敗」複選框。你使用最新版本的Slack插件嗎? – Riduidel

+0

@Riduidel,你可以在這裏看到這個複選框? – kivagant

+0

我有一個2.0.1版本的Slack通知插件 – kivagant

回答

21

你可以這樣做,並使用try catch塊。

下面是一些例子代碼:

node { 
    try { 
     notifyBuild('STARTED') 

     stage('Prepare code') { 
      echo 'do checkout stuff' 
     } 

     stage('Testing') { 
      echo 'Testing' 
      echo 'Testing - publish coverage results' 
     } 

     stage('Staging') { 
      echo 'Deploy Stage' 
     } 

     stage('Deploy') { 
      echo 'Deploy - Backend' 
      echo 'Deploy - Frontend' 
     } 

    } catch (e) { 
    // If there was an exception thrown, the build failed 
    currentBuild.result = "FAILED" 
    throw e 
    } finally { 
    // Success or failure, always send notifications 
    notifyBuild(currentBuild.result) 
    } 
} 

def notifyBuild(String buildStatus = 'STARTED') { 
    // build status of null means successful 
    buildStatus = buildStatus ?: 'SUCCESSFUL' 

    // Default values 
    def colorName = 'RED' 
    def colorCode = '#FF0000' 
    def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'" 
    def summary = "${subject} (${env.BUILD_URL})" 

    // Override default values based on build status 
    if (buildStatus == 'STARTED') { 
    color = 'YELLOW' 
    colorCode = '#FFFF00' 
    } else if (buildStatus == 'SUCCESSFUL') { 
    color = 'GREEN' 
    colorCode = '#00FF00' 
    } else { 
    color = 'RED' 
    colorCode = '#FF0000' 
    } 

    // Send notifications 
    slackSend (color: colorCode, message: summary) 
} 

完整的片段可以在這裏Jenkinsfile Template

+0

謝謝你,@ Fahl-Design,我會稍後再試,並且會給你寫結果。 – kivagant

+1

它的工作!^_^ – kivagant

+0

太棒了!享受;)正如你可以在這段代碼中看到的,你可以添加任何其他通知服務slackSend –

14

基於Liam Newman's blog post找到,看看這個清理片段只鬆弛。它採用原Jenkins results,消息格式,更好的顏色(基於EclEmma),以及一些Groovy的功能,如default arguments

def notifySlack(String buildStatus = 'STARTED') { 
    // Build status of null means success. 
    buildStatus = buildStatus ?: 'SUCCESS' 

    def color 

    if (buildStatus == 'STARTED') { 
     color = '#D4DADF' 
    } else if (buildStatus == 'SUCCESS') { 
     color = '#BDFFC3' 
    } else if (buildStatus == 'UNSTABLE') { 
     color = '#FFFE89' 
    } else { 
     color = '#FF9FA1' 
    } 

    def msg = "${buildStatus}: `${env.JOB_NAME}` #${env.BUILD_NUMBER}:\n${env.BUILD_URL}" 

    slackSend(color: color, message: msg) 
} 

node { 
    try { 
     notifySlack() 

     // Existing build steps. 
    } catch (e) { 
     currentBuild.result = 'FAILURE' 
     throw e 
    } finally { 
     notifySlack(currentBuild.result) 
    } 
} 

輸出會是這樣(玩不同的格式樣式here):

也許env.JOB_NAME包含編碼的斜槓(%2F),其可以被固定爲replaceAll("%2F", "/")

查看this Gist以查看如何通知HipChat。

+0

Liam的文章似乎不可用了。 – Amida

+1

@Amida謝謝你的提示,修正它。 – beatngu13

相關問題