rgov
rgov

Reputation: 4349

Setting a per-node environment variable in a pipeline job

My Jenkins pipeline looks something like this (please forgive small syntax errors):

def buildsToDo = "foo bar".tokenize()
def buildPlan = [:]

for (int i = 0; i < buildsToDo.size(); i ++) {
  def tag = buildsToDo[i]

  buildPlan[tag] = {
    node(tag) {
      env.ENVVAR = tag
      stage("build " + tag) {
        sh 'env'
      }
    }
  }
}

parallel(buildPlan)

My intention is to have one node with ENVVAR=foo and one with ENVVAR=bar.

What I actually see is that when the env command runs, ENVVAR=bar is set on both nodes.

According to this tutorial, "properties of [the special variable env] are environment variables on the current node." So I'd expect this to work.

Upvotes: 1

Views: 4031

Answers (2)

agg3l
agg3l

Reputation: 1444

Jenkins pipline plugin is yound and far from being stable for now (as I can say). CPS concept they try to apply affects execution in many ways as well, I've had may exiting moments with it so far (while it is really great same time, indeed)

You might want to try to adjust your code as following, running required commands within 'withEnv' block. Moving volatile variables out of parallel block helps as well:

def buildsToDo = "foo bar".tokenize()
def buildPlan = [:]

for (int i = 0; i < buildsToDo.size(); i ++) {
  def tag = buildsToDo[i]
  buildPlan[tag] = {
    node(tag) {
      // Note environment is modified here !
      withEnv(env + [ENVVAR=tag]) {
          stage("build " + tag) {
            sh 'env'
          }
       }
    }
  }
}

parallel(buildPlan)

Upvotes: 2

rgov
rgov

Reputation: 4349

Much later on in the tutorial, it says:

Do not use env in this case:

env.PATH = "${mvnHome}/bin:${env.PATH}"

because environment variable overrides are limited to being global to a pipeline run, not local to the current thread (and thus agent). You could, however, use the withEnv step as noted above.

Looks like an ugly limitation of the DSL. It works wrapping the stage in a withEnv step.

Upvotes: 1

Related Questions