小编典典

Jenkins-尝试捕获特定阶段和后续条件步骤

jenkins

我正在尝试在前一个阶段周围使用try / catch来复制Jenkins管道中条件阶段的等效内容,然后在该阶段之前设置一个成功变量,该变量用于触发条件阶段。

看起来,尝试catch块是可行的方法,将成功var设置为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{

我也尝试了很多变化。

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

谢谢。


阅读 525

收藏
2020-07-25

共1个答案

小编典典

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

因此,在这里,第二阶段仅在测试通过时运行,并且无论以下情况如何,都会记录测试结果:

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在声明性管道中使用,但是就像StephenKing所说的那样,您不能只直接使用try(必须在脚本步骤中包装任意的Groovy代码)。

2020-07-25