0

In a Jenkins freestyle job (on an older 1.6x version, no support for 2.x pipeline jobs) I would like to run a shell command (curl -XPOST ...) as a post build step if the build status recovered(!) from FAILED to SUCCESS.

However, all plugins for determining the build status I am aware of can only do something if the current build status IS FAILED or SUCCESS but don't take into account whether it recovered in comparison to the last build.

Is there any way how to achieve this, e.g. using the Groovy Post build plugin and some lines of scripting?

Dirk
  • 9,381
  • 17
  • 70
  • 98

2 Answers2

2

I found that something like this is a good way to go. You can build up some interesting logic, and the "currentBuild" variable has some decent documentation here: currentBuild variable doc

    script {
       if ( ( currentBuild.resultIsBetterOrEqualTo("SUCCESS") && currentBuild.previousBuild.resultIsWorseOrEqualTo("UNSTABLE") ) || currentBuild.resultIsWorseOrEqualTo("UNSTABLE")) {
         echo "If current build is good, and last build is bad, or current build is bad"
       }
    }
user2312718
  • 41
  • 1
  • 5
1

Meanwhile I found a way to achieve this. It is not necessarily pretty and I still appreciate alternative solutions :)

First of all, a plugin is needed which lets you execute shell commands in a Post Build step. There might be different ones, I am using the PostBuildScript plugin for that.

Then, create a "Execute a set of scripts" post build step, set the step to execute to Build step and select Execute shell, for me this looks like this: Jenkins post build step

In there, I run the following shell script lines which use my Jenkins server's REST API in combination with a Python one-liner (you could also use jq or something else for this) to determine the status of the current build as well as of the last completed build:

statusOfCurrentBuild=$(curl --silent "${BUILD_URL}api/json" | python -c "import sys, json; print json.load(sys.stdin)['result']")
statusOfLastBuild=$(curl --silent "${JOB_URL}/lastCompletedBuild/api/json" | python -c "import sys, json; print json.load(sys.stdin)['result']")

if [ "${statusOfCurrentBuild}" == "SUCCESS" ] && [ "${statusOfLastBuild}" == "FAILURE" ]
then
    echo "Build was fixed"
    # do something interesting here
fi

Depending on your Jenkins settings, using the REST API might require authentication.

Dirk
  • 9,381
  • 17
  • 70
  • 98