How to pass in a variable to docker args in a Jenkins declarative pipeline

Viewed 6038

I'm creating a Jenkins declarative pipeline job where I run some node tests within a docker container that depends on an external db container. I create a unique network and then attempt to pass the network uid in as a docker arg so that the docker container can access said db container:

def myNetwork = dbNetwork
stage('test-ci') {
      agent {
        docker {
          reuseNode true
          image 'myrepo/my-nodejs'
          label 'docker'
          args "--net ${myNetwork}"
        }
      }
      steps {
          script {
            try {
              sh 'npm run test-ci'
            } catch(err) {
              currentBuild.result = 'FAILED'
            }
          }
        }
    }

However, Jenkins output shows that the variable somehow ends up being null by the time docker receives it:

$ docker run -t -d -u 233:233 --net null -w /home/jenkins/workspace/es_feature_add-db-container- ...

I did note that the example demonstrating passing args uses single quotes, but I need double quotes so myNetwork properly expands, but perhaps this isn't the pipeline way.

How can I properly pass a variable to docker?

EDIT: After playing around a little more, I think this is a scope issue since I'm successfully able to pass environment variables like env.BUILD_TAG. I basically just need a random, guaranteed unique network name for a given job run so I don't have collisions with other jobs - env.BUILD_TAG seems to do the job, but I'd still like to know why I can't pass in a variable that I define in the script.

1 Answers

Create an environment section - this is the way to bridge Groovy and in-Jenkins Shell

String SomeVar = "wibble"

pipeline {
...
    environment {
    // use a Groovy GString here
    SomeVar = "$SomeVar"
    // mix with the environment in "shell jenkins" 
    MyBuild = "$SomeVar-$GIT_COMMIT" 
    }
}
 stage(DockerBuild) {
     echo 'this is a groovy level call - so' +  env.SomeVar  + 'will work'
 }

In short we can have a variable in Grtoovy segment, and in the pipeline portion still access it in Shell and if we need to use groovy level calls (usually docker.build) the varible is in env.Varname

Related