jenkins-groovyxen

Understanding Groovy retry() and catchError()


I have this Jenkins pipeline that executes terraform init, terraform plan and terraform apply to deploy some VMs on unpowered Xen Orchestra (XO). My XO server is very limited in resources and one needs to re-run the terraform apply a few times to get all the VMs to launch successfully. I tried to implement these re-runs with Groovy retry(). Here is the pertinent part of the pipeline:

stage("Terraform apply") {
  steps {
    script {
      def maxRetries = 10
      def retryCount = 0
      dir('dev/xo/clusters/sandbox') {
        withCredentials([string(credentialsId: 'XOA_PASSWORD', variable: 'xoaPassword')]){
          retry(maxRetries) {
            retryCount++
            echo "Terraform apply. Attempt $retryCount of $maxRetries"
            catchError {
              sh '''
              export XOA_PASSWORD="${xoaPassword}"
              terraform apply -parallelism=1 -no-color "theplan"
              '''
            }
          }
        }
      }
    }
  }

When run the above, the first "try" fails but there is no "retry" and whole pipeline exits with error. What am I doing wrong?


Solution

  • Your catchError block catches the exception and sets the build status to error and the build continues at the end of that block. That is within your retry block, so you are expecting the retry block to catch the exception, but since it has already been caught, it can't. Yes, the build status is error, but the Retry would only retry upon exception, not on build status error.

    So, you should be able to remove the catchError, and leave the exception to be caught by the retry block.