仅当前一阶段在 Jenkins 脚本化管道中成功时才运行阶段

2024-04-21

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

node ('docker2') {

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

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

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

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


詹金斯管道中没有成功步骤或失败步骤的概念。只有构建的状态(成功、失败、不稳定等)

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

第一的。如果测试失败(使用“错误”詹金斯步骤),您的管道可能会失败。例如:

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

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

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

或者,如果您的命令在测试失败时传播错误(例如“mvn test”),那么您可以这样写:

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

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

stage('Push Artifacts') {

}

在这些情况下,当测试失败时,您的管道也会失败。并且不会执行“测试”阶段之后的任何阶段。

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

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
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅当前一阶段在 Jenkins 脚本化管道中成功时才运行阶段 的相关文章

随机推荐