2016-12-01 241 views
7

在我們的Jenkins管道工作中,我們有幾個階段,我想要的是如果任何階段失敗,然後停止構建並且不繼續到更遠的階段。暫時停止jenkins管道工作

這裏是一個階段的一個例子:

stage('Building') { 
    def result = sh returnStatus: true, script: './build.sh' 
    if (result != 0) { 
     echo '[FAILURE] Failed to build' 
     currentBuild.result = 'FAILURE' 
    } 
} 

該腳本將失敗,並構建結果將更新,但作業繼續到下一個階段。發生這種情況時,我該如何中止或停止工作?

回答

7

基本上這就是sh步驟所做的。如果你不抓住,結果在一個變量,你可以運行:

sh "./build" 

如果腳本reurns非零退出代碼這將退出。

如果你需要首先做的東西,需要捕捉的結果,你可以使用一個shell步驟辭職

stage('Building') { 
    def result = sh returnStatus: true, script: './build.sh' 
    if (result != 0) { 
     echo '[FAILURE] Failed to build' 
     currentBuild.result = 'FAILURE' 
     // do more stuff here 

     // this will terminate the job if result is non-zero 
     // You don't even have to set the result to FAILURE by hand 
     sh "exit ${result}" 
    } 
} 

但下面就給你一樣,但似乎更理智來做

stage('Building') { 
    try { 
     sh './build.sh' 
    } finally { 
     echo '[FAILURE] Failed to build' 
    } 
} 

也可以在你的代碼中調用return。但是,如果你在stage之內,它只會退出該階段。所以

stage('Building') { 
    def result = sh returnStatus: true, script: './build.sh' 
    if (result != 0) { 
     echo '[FAILURE] Failed to build' 
     currentBuild.result = 'FAILURE' 
     return 
    } 
    echo "This will not be displayed" 
} 
echo "The build will continue executing from here" 

不會退出工作,但

stage('Building') { 
    def result = sh returnStatus: true, script: './build.sh' 
} 
if (result != 0) { 
    echo '[FAILURE] Failed to build' 
    currentBuild.result = 'FAILURE' 
    return 
} 

意志。

3

實現此行爲的另一種方法是拋出異常。事實上,這正是詹金斯本身所做的。這樣,您也可以將構建狀態設置爲ABORTEDFAILURE。這個例子中止構建:

stage('Building') { 
    currentBuild.rawBuild.result = Result.ABORTED 
    throw new hudson.AbortException('Guess what!') 
    echo 'Further code will not be executed' 
} 

輸出:

[Pipeline] stage 
[Pipeline] { (Building) 
[Pipeline] } 
[Pipeline] // stage 
[Pipeline] End of Pipeline 
ERROR: Guess what! 
Finished: ABORTED 
+0

隨着詹金斯2.89.3這是一個錯誤:'org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:不允許腳本使用新hudson.AbortException java.lang.String' –

+0

看起來沙箱模式已啓用,並禁止拋出該異常。這種奇怪的,但禁用沙盒模式應該做的伎倆。 – Jazzschmidt

+0

或者,您可以通過Manage Jenkins>進程內腳本審批來允許使用 – Jazzschmidt