I want to do some Docker cleanup steps before a Jenkins build. This is the build step:
steps {
script {
try {
sh '''
docker container stop $(docker ps -q)
docker rm $(docker ps -aq)
docker rmi -f $(docker images -q)
docker build -f Dockerfile_build | tee buildlog.txt
'''
} catch(err) {
echo err.getMessage()
}
}
}
The first lines of the sh
part may fail, causing the whole build to fail:
[Pipeline] sh
docker ps -q
docker container stop Error: you must provide at least one name or id
[Pipeline] echo
script returned exit code 125
However, that only means that there's no cleanup to do. I want to continue the build job, no matter how many of the first three lines fail. My question is whether I have to put each of them in its own try/catch block, or if there's a more concise way of saying "try these and ignore any errors".
CodePudding user response:
If you want to continue your script even if you get errors for individual commands you can set e
in your script, but the sh
step will never error out. You can also ignore first 3 commands and then error out the last command as well by setting -e
and removing it. See the example below.
sh '''
#!/bin/bash
set e
docker container stop $(docker ps -q)
docker rm $(docker ps -aq)
docker rmi -f $(docker images -q)
set -e
docker build -f Dockerfile_build | tee buildlog.txt
'''