Setting a per-node environment variable in a pipeline job

天涯浪子 提交于 2019-12-12 03:43:38

问题


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.


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/39986628/setting-a-per-node-environment-variable-in-a-pipeline-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!