How to prevent running a Jenkins job if another job has failed

For my automated tests to run on regular basis (e.g. every night at 1am), I have created to Jenkins jobs:
1) Job to compile the build, which will be used to run my automation against
2) Job that actually runs my automated tests

My constraints were as follows:
1) If compile build has failed, automation build should not be executed and should be failed with an appropriate message
2) If compile build succeeds, automation build should download compiled binaries and work with them.

There are couple of ways of downloading the binaries:
1) If both of your builds are on the same server, you can most definitely reference the location of the second build from your current build and gain access to the compilation output or
2) You can dynamically download compiled binaries, which will not tie you down to a single server. This is very useful if you have a farm of Jenkins servers and you do not know which server compiles your build.

So, without any further adue, here is the script that I am using in my production environment:

SERVER="<a href="http://my.jenkins-server.com"
JOB="MyCompileJobName"
 
#">http://my.jenkins-server.com"
JOB="MyCompileJobName"
 
#</a> Test to see if last build has passed of failed by analyzing the XML of the last result.
if [[ `curl --silent ${SERVER}/job/${JOB}/lastBuild/api/xml` =~ "<result>FAILURE</result>" ]]
then
  echo "******** ${JOB} build failed ***********"
  exit 1
fi
 
# extract name of last build
LASTNAME=`curl --silent ${SERVER}/job/${JOB}/lastBuild/api/xml | grep -oP "<fullDisplayName>\K.*?(?=</fullDisplayName>)"`
 
# extract url of last build
URL=`curl --silent ${SERVER}/job/${JOB}/lastBuild/api/xml | grep -oP "<url>\K.*?(?=</url>)"`
 
STR="####### Using binaries from build: $LASTNAME ($URL) #######"
STARS=`seq -s# ${#STR} | tr -d '[:digit:]'`
echo $STARS
echo $STR
echo $STARS
 
# Download last build binaries
curl --silent -o artifacts.zip ${SERVER}/job/${JOB}/lastSuccessfulBuild/artifact/*zip*/archive.zip
unzip -q artifacts.zip
mv ${WORKSPACE}/archive/output ${WORKSPACE}
rm -rf archive artifacts.zip

I hope this helps!

Comments