凡放在Jenkinsfile的try / catch

Hen*_*nry 5 groovy jenkins jenkins-pipeline

在哪里放置try / catch,使其可以按预期工作,特别是在存在并行分支的情况下工作?(此外,还有蓝海插件)

在有关Jenkinsfile的官方文档中,该主题没有任何明确内容,但是确实存在示例:

示例1:尝试在阶段块内

Jenkinsfile (Scripted Pipeline)
node {
stage('Example') {  //It's inside the stage block
    try {
        sh 'exit 1'
    }
    catch (exc) {
        echo 'Something failed, I should sound the klaxons!'
        throw
    }
}
}
Run Code Online (Sandbox Code Playgroud)

示例2:尝试在节点块内部

Jenkinsfile (Scripted Pipeline)
stage('Build') {
    /* .. snip .. */
}

stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    },
    windows: {
        node('windows') {
            /* .. snip .. */
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

因此,就我而言,它是否可以这种方式工作(这是最外面的障碍)?基本上,这是一个嵌套的并行构建。我观察到,有时当其中一个分支发生故障时,整个构建过程会继续进行,并且管线图仍然在蔚蓝的大海中呈绿色:(如果try / catch这样工作,那么我可以尝试其他可能性)

try{
    parallel 'b0': {
        node('parallel'){
            ....
        }
    }, 'b1': {
        node('parallel'){
            ....
        }
    }, 'b2': {
       parallel 'b2-0': {
           node('parallel'){           
               ....
           }
       }, 'b2-1': {
           node('parallel'){
             ....
           }
       }, failFast: true

       parallel 'anotherb0': {
           node('parallel'){
                .....
           }
       }, 'anotherb1': {
           node('parallel'){
               ....
           }
       }, failFast: true
    }, failFast: true
}catch(err){
    print err
    currentBuild.result = 'FAILURE'
}finally{
}
Run Code Online (Sandbox Code Playgroud)

And*_*ray -2

建议使用声明式管道而不是脚本式管道。

您将专注于编写您希望使用的每个插件提供的特定管道语法支持。每个都有相似但特定的语法来实现其特定目的。

也就是说,有时您必须在脚本块中编写一小段脚本。我从未使用过 try catch,并且怀疑如果您遵循每个插件提供的语法支持(应该在插件网站上为每个插件单独记录),那么您是否需要这样做。

pipeline {
    stages {
        stage ("Do Something") {
            steps {
                bat "..."
                script {
                  //Code that requires a script tag to be present if it can't be done by a plugin's native pipeline support.
                } 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)