Running a Docker container from a Jenkins pipeline, and capture the output

Viewed 5840

In a Jenkinsfile, how can I run a Docker container and capture the output, without reverting to sh instructions?

This is how I build my container image during the Build stage:

dockerImage = docker.build(env.DOCKER_COORDS, "--build-arg BUILD_VERSION=${env.BUILD_VERSION} .")

And this is how I push the image in a later Publish stage:

withDockerRegistry(credentialsId: env.DOCKER_REG_CREDS_ID) {
    dockerImage.push('latest')
}

In between the Build and Publish stages, in a Test stage, I would like to validate that the output from the container, when passing a --version argument, is equal to ${env.BUILD_VERSION}.

How can I run the container and capture the output, without having to use sh "docker ..." instructions again?

2 Answers

I am new to this but according to the documentation of Docker Pipeline plugin, you can use Image.run([args]), for your case it will be dockerImage.run()

To pass environment variables:

dockerImage.run(['-e your_variable=X'])

Normally you can run and capture the output using the sh method (on a Linux slave and bat for windows). For example, to retrieve the python version of the official python docker, it will look like this:

def version = sh label: '', returnStdout: true, script: 'docker run python python --version'

And then you could just compare the output of the commande with ${env.BUILD_VERSION}. This shouldn't be to different with your docker image.

Related