How to catch manual UI cancel of job in Jenkinsfile

后端 未结 2 1922
深忆病人
深忆病人 2021-01-01 23:20

I\'ve tried to find documentation about how in a Jenkinsfile pipeline catching the error that occurs when a user cancels a job in jenkins web UI.

I haven\'t got the

相关标签:
2条回答
  • 2021-01-02 00:13

    Non-declarative approach:

    When you abort pipeline script build, exception of type org.jenkinsci.plugins.workflow.steps.FlowInterruptedException is thrown. Release resources in catch block and re-throw the exception.

    import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
    
    def releaseResources() {
      echo "Releasing resources"
      sleep 10
    }
    
    node {
      try {
        echo "Doing steps..."
      } catch (FlowInterruptedException interruptEx) {
        releaseResources()
        throw interruptEx
      }
    }
    

    Declarative approach (UPDATED 11/2019):

    According to Jenkins Declarative Pipeline docs, under post section:

    cleanup

    Run the steps in this post condition after every other post condition has been evaluated, regardless of the Pipeline or stage’s status.

    So that should be good place to free resources, no matter whether the pipeline was aborted or not.

    def releaseResources() {
      echo "Releasing resources"
      sleep 10
    }
    
    pipeline {
      agent none
      stages {
        stage("test") {
          steps {
            parallel (
              unit: {
                node("main-builder") {
                  script {
                    echo "Doing steps..."
                    sleep 20
                  }
                }
              }
            )
          }
          post {
            cleanup {
              releaseResources()
            }
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-02 00:17

    You can add a post trigger "cleanup" to the stage:

    post {
        cleanup {
            script { ... }
            sh "remove lock"
        }
    }
    
    0 讨论(0)
提交回复
热议问题