title: How to dynamically set environment variables in scripted jenkins pipeline?
body: <p>I'm trying to dynamically set environment variables in the jenkins pipeline script.</p>
  
  <p>I'm using a combination of .groovy and .jenkinsfile scripts to generate the stage{} definitions for a pipeline as DRY as possible.</p>
  
  <p>I have a method below:</p>
  
  <pre><code>def generateStage(nameOfTestSet, pathToTestSet, machineLabel, envVarName, envVarValue)
  {
      echo "Generating stage for ${nameOfTestSet} on ${machineLabel}"
      return node("${machineLabel}") {
          stage(nameOfTestSet)
          {
              /////// Area of interest ////////////
              environment {
                  "${envVarName} = ${envVarValue}"
              }
             /////////////////////////////////////
              try {
                  echo "Would run: "+pathToTestSet
  
              } finally {
                  echo "Archive results here"
              }   
          }
      }
  }
  </code></pre>
  
  <p>There's some wrapper code running this, but abstracting away we'd have the caller essentially use:</p>
  
  <pre><code>generateStage("SimpleTestSuite", "path.to.test", "MachineA", "SOME_ENV_VAR", "ENV_VALUE")
  
  </code></pre>
  
  <p>Where the last two parameters are the environment name (<code>SOME_ENV_VAR</code>) and the value (<code>ENV_VALUE</code>)</p>
  
  <p>The equivalent declarative code would be:</p>
  
  <pre><code>stage("SimpleTestSuite")
  {
    agent {
       label "MachineA"
    }
    environment = {
     SOME_ENV_VAR = ENV_VALUE
    }
    steps {
      echo "Would run" + "path.to.test" 
    }
    post {
      always {
        echo "Archive results"
        }
    }
  }
  </code></pre>
  
  <p>However, when running this script, the <code>environment</code> syntax in first code block doesn't seem to affect the actual execution at all. If I echo the ${SOME_ENV_VAR} (or even echo ${envVarName} in case it took this variable name as the actual environment value) they both return null.</p>
  
  <p>I'm wondering what's the best way to make this <code>environment{}</code> section as DRY / dynamic as possible?</p>
  
  <p>I would prefer it if there's an extendable solution that can take in a list of environmentName=Value pairs, as this would be more general case.</p>
  
  <p>Note: I have tried the <code>withEnv[]</code> solution for scripted pipelines, however this seems to have the same issue. </p>