user2891264
user2891264

Reputation: 100

Jenkins pipeline build using Jenkinsfile is not failing

I have a declarative pipeline stage like below,

stage('build') {
    steps {
        echo currentBuild.result
        script {
                try {
                    bat 'ant -f xyz\\build.xml'
                } catch (err) {
                    echo "Caught: ${err}"
                    currentBuild.result = 'FAILURE'
                }
            }
        echo currentBuild.result
    }
}

I expect the pipeline to fail since the build is failing with below message.

BUILD FAILED
C:\...\build.xml:8: The following error occurred while executing this line:
C:\...\build.xml:156: The following error occurred while executing this line:
C:\...\build.xml:111: Problem creating jar: C:\...\xyz.war (The system cannot find the path specified) (and the archive is probably corrupt but I could not delete it)

currentBuild.result is null both the time i print it.
Is the ant call wrong?
Why is the return status not caught automatically by pipeline?
Could the ant call be not returning failed status?

I tried catchError instead of try..catch and still the build failure is not caught.

catchError {
    bat 'ant -f xyz\\build.xml'
}

Upvotes: 1

Views: 2436

Answers (1)

user2891264
user2891264

Reputation: 100

The solution was to add "call" keyword to ant call like below, this propagates the exit code from ant to batch call.

stage('build') {
    steps {
        bat 'call ant -f xyz\\build.xml'
    }
}

There is another solution using batch scripting, see below,
- Jenkinsfile

stage('build') {
    steps {
        bat 'xyz\\build.bat'
    }
}

- build.bat

call ant -f "%CD%\xyz\build.xml"
echo ELVL: %ERRORLEVEL% 
IF NOT %ERRORLEVEL% == 0 ( 
    echo ABORT: %ERRORLEVEL%
    call exit /b %ERRORLEVEL%
) ELSE (
    echo PROCEED: %ERRORLEVEL%
)

In this build.bat, if you don't use call keyword, only the first command will be executed and the rest will be ignored. I adapted this directly to ant call in pipeline and it worked.

Upvotes: 3

Related Questions