Monday, June 9, 2014

... I had Jenkins Build Steps Fail Just Because Grep Returned Nothing

All I wanted to do was check if a docker container was running and if it was, stop it.

Simples.

Apparently not :(

Every time the Shell Execution Step with the following code ran, it marked the job as failed, if the docker container wasn't running.

docker ps|grep appserver || true
if [ $? -eq 0 ]; then #appserver container is running - stop it
 docker stop appserver
fi
What isn't immediately obvious with Jenkins' Execute Shell build step is that it is run with -xe arguments.

The -e causes the step to fail for any part of the script that has a return status that isn't 0.

To override the the default behavior, one must add a shebang to the step's code as follows:

#!/bin/sh
docker ps|grep appserver || true
if [ $? -eq 0 ]; then #appserver container is running - stop it
 docker stop appserver
fi
Very annoying, but easily fixed.

2 comments:

  1. All these years later :D Glad it helped!

    ReplyDelete
  2. In my case, I had "#!/bin/bash" at the top of the file, but it wasn't the _first line_. There happened to be an empty first line, and hence the shbang was never recognized. Removed the line (thanks to your post) and voila!

    ReplyDelete