本文介绍了仅在上一阶段在Jenkins脚本化管道中成功时才运行阶段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Jenkins脚本化管道中运行条件步骤,但是我不确定如何仅在上一步成功的情况下运行步骤.例如,在下面的示例中,如果测试"阶段成功,我只想运行推送工件"阶段:

I am trying to run conditional steps in a Jenkins scripted pipeline, however I am not sure how to only run a step if a previous step was successful. For instance, in the following I only want to run the 'Push Artifacts' stage if the 'Test' stage was successful:

node ('docker2') {

    stage ('Build') {
        // build application
    }

    stage ('Test') {
        // run tests
    }

    stage ('Push Artifacts') { 
        if (Tests Were Successful) {  
            // push to artifactory
        }
    }
}

我知道声明性管道允许您使用"post"条件,但是我对Jenkins中的声明性管道与脚本化管道的理解是,脚本化管道提供了更大的灵活性.有没有一种方法可以根据脚本化管道中其他阶段的成功来运行阶段?

I know that declarative pipelines allow you to use 'post' conditions, but my understanding of declarative vs. scripted pipelines in Jenkins is that scripted pipelines offer more flexibility. Is there a way to run stages based on other stages' success in a scripted pipeline?

推荐答案

jenkins管道中没有成功步骤或失败步骤的概念.只有构建状态(成功,失败,不稳定等)

There is no concept of success step or failed step in jenkins pipeline. There is only status of your build (success, failed, unstable, etc.)

您有两种方法可以解决问题:

You have two ways to resolve your problem:

首先.如果测试失败(使用错误" jenkins步骤),则可以使管道失败.例如:

First. You can fail your pipeline if test are failed (using 'error' jenkins step). For example:

stage('Build') {
    // build application
}

stage('Test') {
    def testResult = ... // run command executing tests
    if (testResult == 'Failed') {
        error "test failed"
    }
}

stage('Push Artifacts') {
    //push artifacts
}

或者,如果您的命令在测试失败时传播错误(例如"mvn测试"),则您可以这样编写:

Or if your command propagates error when tests are failed (like 'mvn test') then you can write like this:

stage('Build') {
    // build application
}

stage('Test') {
    sh 'mvn test'
}

stage('Push Artifacts') {

}

在这些情况下,如果测试失败,您的管道将失败. 测试"阶段之后的任何阶段都不会执行.

In these cases your pipeline will be failed when tests are failed. And no stage after 'Test' stage will be executed.

第二.如果只想执行某些步骤,则应根据执行的步骤将测试结果写入变量.您可以在运行步骤之前分析该变量的值.例如:

Second. If you want to run only some steps, depending on the step you performed you should write test result into variable. And you can analyse value of that variable before running steps. For example:

stage('Build') {
    // build application
}

boolean testPassed = true
stage('Test') {
    try{
        sh 'mvn test'
    }catch (Exception e){
        testPassed = false
    }
}

stage('Push Artifacts') {
    if(testPassed){
        //push to artifactory
    }
}

这篇关于仅在上一阶段在Jenkins脚本化管道中成功时才运行阶段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 16:40