Nathan Thompson
Nathan Thompson

Reputation: 2384

How do I fail a Jenkins build if a Docker Pipeline Plugin withRun command returns a non-zero exit code?

I'm using the Docker Pipeline Plugin to execute my build scripts via Docker containers. I noticed that if I had a script return a non-zero exit code when executing within an inside() command, Jenkins would mark the pipeline execution as a failure. This example Jenkinsfile illustrates that scenario:

docker.image('alpine').inside() {
  sh 'exit 1'
}

However, if I use the withRun() command, a similar Jenkinsfile will not cause the build to fail, even though the docker ps -l command shows that the container exited with a non-zero status:

node() {
  sh 'touch ./test.sh'
  sh 'echo "exit 1" >> ./test.sh'
  sh 'chmod 755 ./test.sh'

  docker.image('alpine').withRun("-v ${WORKSPACE}:/newDir", '/bin/sh /newDir/test.sh') {container ->
    sh "docker logs ${container.id} -f"
    sh 'docker ps -l'
  }
}

Is there a way to make withRun() fail the build if the container exits with a non-zero code?

Upvotes: 5

Views: 6704

Answers (3)

yktoo
yktoo

Reputation: 2986

How about running a script that exits based upon the output from docker wait?

sh "exit \$(docker wait ${container.id})"

wait prints the container's exit code, which in case of error causes the build to fail according to sh docs:

Normally, a script which exits with a nonzero status code will cause the step to fail with an exception.

Upvotes: 1

VictorB
VictorB

Reputation: 156

One of possible solutions:

docker.withRegistry("https://${REGISTRY}", 'creds-id') {

    stage("RUN CONTAINER"){
        Image = docker.image("${IMAGE}-${PROJECT}:${TAG}")
        try {
            c = Image.run("-v /mnt:/mnt")
            sh "docker logs -f ${c.id}"
            def out = sh script: "docker inspect ${c.id} --format='{{.State.ExitCode}}'", returnStdout: true
            sh "exit ${out}"
        } finally {
            c.stop()
        }
    }
}

Upvotes: 4

Nathan Thompson
Nathan Thompson

Reputation: 2384

I couldn't find any more information on exit codes from the withRun() command, so I ended up just executing a docker run command from an sh step:

node() {
  sh 'touch ./test.sh'
  sh 'echo "exit 1" >> ./test.sh'
  sh 'chmod 755 ./test.sh'
  sh "docker run --rm -v ${WORKSPACE}:/newDir alpine /bin/sh /newDir/test.sh"
}

Upvotes: 2

Related Questions