Jenkins管道 - 尝试捕获特定阶段和随后的条件步骤

时间:2017-04-08 11:28:14

标签: jenkins jenkins-pipeline

我正在尝试使用前一阶段的try / catch复制Jenkins管道中的条件阶段的等价物,然后设置成功变量,用于触发条件阶段。

看来try catch块是要走的路,将成功变量设置为SUCCESS或FAILED,稍后将其用作when语句的一部分(作为条件阶段的一部分)。

我使用的代码如下:

pipeline {
    agent any
    stages {
        try{
            stage("Run unit tests"){
                steps{
                    sh  '''
                        # Run unit tests without capturing stdout or logs, generates cobetura reports
                        cd ./python
                        nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
                        cd ..
                    '''
                    currentBuild.result = 'SUCCESS'
                }
            }
        } catch(Exception e) {
            // Do something with the exception 
            currentBuild.result = 'SUCCESS'
        }

        stage ('Speak') {
            when {
                expression { currentBuild.result == 'SUCCESS' }
            }
            steps{
                echo "Hello, CONDITIONAL"
            }
        }
    }
}

我收到的最新语法错误如下:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup 
failed:
WorkflowScript: 4: Expected a stage @ line 4, column 9.
       try{

我也尝试了很多变化。

我在这里采取了错误的做法吗?这似乎是一个相当普遍的要求。

感谢。

1 个答案:

答案 0 :(得分:20)

这可能会解决您的问题,具体取决于您的目标。阶段仅在前面的阶段成功时运行,因此如果您实际上有两个阶段(如示例中),并且如果您希望第二阶段仅在第一阶段成功时运行,则您希望确保第一阶段在测试失败时适当地失败。捕获将阻止(理想的)失败。最后将保留失败,并且仍然可以用来获取测试结果。

所以在这里,第二阶段只会在测试通过时运行,测试结果将被记录,无论如何:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

请注意,我实际上在声明性管道中使用try,但like StephenKing says,您不能直接使用try(您必须在脚本中包含任意groovy代码)工序)。