Krishna
Krishna

Reputation: 3177

Retry and timeout in Jenkins DSL Pipeline job

I have a logic for deployment on certain environment that I need to retry. And that logic have some timeout too. So I wrote the DSL code as below:

     Pipeline {
      stages {
       stage('Promote To Stage2 Environment') {
          options {
            timeout(time: "${env.STAGE_TIME_OUT}", unit: "HOURS")
            retry("${env.RETRY_COUNT}")
          }
          steps {
            script {
              //my logic
            }
         }
       }
     }
   }

Now , I need to perform rollback action and need to terminate pipeline job, in case retry exceeded or timeout exceeded while doing deployment on particular environment. So I modified the code as below:

  pipeline {
    stages {
      stage('Promote To Stage2 Environment') {
          steps {
            script {
              try {
                timeout(time: "${env.STAGE_TIME_OUT}", unit: "HOURS") {
                  retry("${env.RETRY_COUNT}") {
                    //my logic
                    }
                  }
                }
              } catch (err) {
                //Need rollback. action to be required , in case retry exceeded or timeout happen
                performRollBack('env')
                error('Deployment on Stage1 failed..... Build rolled back....')
              }
            }
          }
        }
    }
    

Is this is a right way, or something I am missing.

Upvotes: 0

Views: 2440

Answers (1)

Samit Kumar Patel
Samit Kumar Patel

Reputation: 2098

you can also do like below example:

pipeline {
    agent any
    stages {
        stage('debug') {
            options {
                timeout(time: 10, unit: 'SECONDS')
                retry(2)
            }
            steps {
                // uncomment below to check post failure  
                sh "exit 1"
                
                // uncomment below to check post unsuccessful scenario
                //sleep 100
            }
        }
    }
    post { 
        always { 
            echo 'I will execute always'
        }
        failure {
            echo 'I will execute if a failure occured'
        }
        unsuccessful {
            echo 'I will execute if a job is timedout and failed'
        }
    }
}

Retry scenario the output will be

enter image description here

Timeout scenario the output will be

enter image description here

you can find more post build action here

Upvotes: 0

Related Questions