Jenkinsfile: how to capture stdout of docker.Image.run()?

I would like to use Jenkins docker.Image.run() to run GitVersion.

From a bash shell, if I run

docker run --rm -v "$(pwd):/repo" gittools/gitversion:5.6.6 /repo

…a JSON-format string gets sent to stdout.

I’d like my Jenkinsfile to consume this stdout.
I know that I can run this docker container from my Jenkinsfile as follows:

pipeline {
  agent any
  stages {
    stage("1") {
      steps {
        script {
          def img = docker.image("gittools/gitversion:5.6.6")
          img.run('-v "$(pwd):/repo"', '/repo')
        }
      }
    }
  }
}

How can I capture the stdout of the run container using docker.Image.run()?

I know I can probably capture the container’s stdout by invoking sh, e.g.

def my_stdout = sh(script: 'docker run --rm -v "$(pwd):/repo" gittools/gitversion:5.6.6 /repo`,
                   returnStdout:true)

…but I’d like to learn, specifically, if possible/how to capture the stdout from Jenkins’ docker.Image.run(), as described at ${JENKINS_URL}/job/${job}/pipeline-syntax/globals#docker

Source: Docker Questions

LEAVE A COMMENT