Home > Blockchain >  Cannot retrieve shell script status in the catch block of groovy/jenkins docker file
Cannot retrieve shell script status in the catch block of groovy/jenkins docker file

Time:03-12

I am trying to populate a global variable with the exit code status and use that in the catch block to avoid certain exceptions. Not able to store the exit code value to the variable in groovy docker file. Should I take a different approach here? Please suggest.

Scenario: I'm looking to make sure if docker command fails, it should not fail the build, but if the python command inside the sh""" inside docker.image.inside fails as shown below, only then it should fail the build. That's why I started looking for exit code of python script to just fail the build when python cmd is failed and not otherwise.

def scriptStatus = 0

stages {
stage('Call Update) {
  steps {
    script {
        try {
            def image = docker.image("${repo}:${tag}")
            image.pull()
            image.inside("--env-file ${PWD}/cc.env -v /work/user.ssh") {
            scriptStatus = sh(script: """
                python -u /config/env-python/abc.py
            """, returnStdout: true)
            }
        } catch(Exception e) {
            echo "scriptStatus = ${scriptStatus}" --> not showing any result
            if (scriptStatus == 0){
            currentBuild.result = 'SUCCESS'
            } else {
            currentBuild.result = 'FAILURE'
            }
       }
    }
  }
}
}

I have tried couple options here:

returnStatus: true -> but it doesn't export any result outside the try block, hence I can't check whether the returned value is 0 or non-zero.

then I also tried exitCode=$? -> this also doesn't get stored in the global variable which can be further used in the catch block for if/else condition.

CodePudding user response:

Use returnStatus: true instead returnStdout: true

scriptStatus = sh(script: """
                python -u /config/env-python/abc.py
            """, returnStatus: true)

returnStatus : returns the status code either 0 or 1.

returnStdout: returns the output.

CodePudding user response:

You need to declare the variable outside the scope of the try block, and modify the sh step method argument from returnStdout to returnStatus:

script {
    int scriptStatus
    try {
        def image = docker.image("${repo}:${tag}")
        image.pull()
        image.inside("--env-file ${PWD}/cc.env -v /work/user.ssh") {
        scriptStatus = sh(script: """
            python -u /config/env-python/abc.py
        """, returnStatus: true)
        }
    } catch(Exception e) {
        echo "scriptStatus = ${scriptStatus}" --> not showing any result
        if (scriptStatus == 0){
        currentBuild.result = 'SUCCESS'
        } else {
        currentBuild.result = 'FAILURE'
      }
   }
}
  • Related