2016-04-25 28 views
12

如果Jenkinsfile中的構建失敗,是否有執行清理(或回滾)的方法?如何在Jenkinsfile中執行失敗的構建操作

我想通知我們的Atlassian Stash實例構建失敗(通過在正確的URL處執行curl)。

基本上,這是構建狀態設置失敗後的後續步驟。

我應該用try {} catch()?如果是這樣,我應該捕獲什麼樣的異常類型?

回答

17

我目前也在尋找解決這個問題的辦法。到目前爲止,我能想到的最好的方法是創建一個包裝函數,它在try catch塊中運行管道代碼。如果您還想通知成功,則可以將Exception存儲在變量中,並將通知代碼移至finally塊。另外請注意,您必須重新拋出異常,以便Jenkins認爲構建失敗。也許有些讀者會發現這個問題更加優雅的方法。

pipeline('linux') { 
    stage 'Pull' 
    stage 'Deploy' 
    echo "Deploying" 
    throw new FileNotFoundException("Nothing to pull") 
    // ... 
} 

def pipeline(String label, Closure body) { 
    node(label) { 
     wrap([$class: 'TimestamperBuildWrapper']) { 
      try { 
       body.call() 
      } catch (Exception e) { 
       emailext subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - FAILURE (${e.message})!", to: "[email protected]",body: "..." 
       throw e; // rethrow so the build is considered failed       
      } 
     } 
    } 
} 
+3

獎勵積分對於'TimestamperBuildWrapper',我不知道它存在 –

+0

我在終於在我的幾個地方嘗試{} {}詹金斯文件,它奇妙地工作。我還想指出,try/catch/finally塊不需要將**分解爲單獨的函數或包裝函數 - 它們在腳本管道中的任何地方都能正常工作。 – jayhendren

11

自2017-02-03以來,Declarative Pipeline Syntax 1.0可用於實現此後構建步驟功能。

這是一種用於構建管道的新語法,它擴展了Pipeline的預定義結構和一些新的步驟,使用戶能夠定義代理,發佈操作,環境設置,證書和階段。

下面是一個簡單Jenkinsfile與聲明語法:

pipeline { 
    agent label:'has-docker', dockerfile: true 
    environment { 
    GIT_COMMITTER_NAME = "jenkins" 
    GIT_COMMITTER_EMAIL = "[email protected]" 
    } 
    stages { 
    stage("Build") { 
     steps { 
     sh 'mvn clean install -Dmaven.test.failure.ignore=true' 
     } 
    } 
    stage("Archive"){ 
     steps { 
     archive "*/target/**/*" 
     junit '*/target/surefire-reports/*.xml' 
     } 
    } 
    } 
    post { 
    always { 
     deleteDir() 
    } 
    success { 
     mail to:"[email protected]", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed." 
    } 
    failure { 
     mail to:"[email protected]", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed." 
    } 
    } 
} 

代碼塊是什麼處理該後一步動作

聲明管道語法引用here

相關問題