Home > Software design >  How to get a post{} section executed in a nested stage{} block in Jenkins?
How to get a post{} section executed in a nested stage{} block in Jenkins?

Time:05-12

How do I get the following post section to run? The idea is to generate parallel running stages as per the contents of myList.

stage("Dynamic stages"){
  steps{
    stageMap = [:]
    script {
      for (element in myList) {
        stageMap[element] = {
          stage("Stage 1 of ${element}"){
            echo "Stage 1"
          }
          stage("Stage 2 ${element}"){
            echo "Stage 2"
            post{
              failure{
                echo "Stage 2 failed!"
              }
            }
          }
        }
      }
    }
    parallel stageMap
  }
}

The build fails with the following error

Also:   java.lang.NoSuchMethodError: No such DSL method 'post' found among steps...

The Jenkins doc however says it is allowed

Sure enough there is a big list of allowed steps and post is not among those. Am I missing something or is the doc not clear about this case?

CodePudding user response:

post{} is only available in declarative pipeline, but not within a scripted section of a declarative pipeline. You can use try{} catch{} instead.

There is another error: You are using loop variable element within a closure, which doesn't work as expected. The closure captures the element variable, but when the closure runs, its value will always be the last value of the loop. To fix this, I have assigned the loop variable to new local variable curElement, which will be a new instance for every iteration, so it gets captured as expected.

stage("Dynamic stages"){
  steps{
    stageMap = [:]
    script {
      for (element in myList) {
        def curElement = element

        stageMap[element] = {
          stage("Stage 1 of ${curElement}"){
            echo "Stage 1"
          }
          stage("Stage 2 ${curElement}"){
            echo "Stage 2"
            try {
                // some steps that may fail
            }
            catch( Exception e ) {
                echo "Stage 2 failed! Error: $e"
                throw  // Rethrow exception, to let the build fail.
            }
          }
        }
      }
    }
    parallel stageMap
  }
}
  • Related