2

I have env vars defined in my environment directive at the top of the pipeline:

environment {
    var1 = 'sdfsdfdsf'
    var2 = 'sssssss'
}

But there are some that I need to dynamically set or override in the stages. But if I use an environment{} directive in a stage the vars won't be accessible to other stages. Initially I thought I could define them all with default values in the top environment directive and overwrite them in the pipeline but this is the behavior I observed:

  1. Define var in environment block
  2. Try to overwrite in script{} block like: script {env.var1 = 'new value'}
  3. The env is not overwritten

How can I change the envs?

red888
  • 27,709
  • 55
  • 204
  • 392

1 Answers1

4

You can do it as follow:

  1. Define var in stage environment { env.var1 = 'value' }
  2. you can access same var in other stages and change value in environment { env.var1 = 'value2' }

     pipeline {
      agent any
      environment { 
         var1 = 'value'
      }
    
      stages {
         stage('Initialize') {
           steps {
            script {
            echo ("value : " + env.var1)
             }
           }
        }
    
        stage('build') {
          environment { 
            var1 = 'value2'
           }
           steps {
            script {
              echo ("value : " + env.var1)
            }
          }
        }
      }
    } 
    
TrafLaw
  • 308
  • 1
  • 9
  • but your just using script{} instead of environment{}. Why are environment{} vars not overwritable in script{}? – red888 Dec 07 '17 at 06:19
  • environment variables cannot be changed from within script{}.You can change them from within environment{} only. – TrafLaw Dec 07 '17 at 06:29
  • right so my question is how do I set the environment var in a stage globally? In you example if i had another stage after "build" and did "echo env.var1" the value would be "value" not "value2" – red888 Dec 07 '17 at 06:49
  • 2
    i see. so the correction solution for you will be to use global variables and not environment variables. Because environment variables are not mutable. – TrafLaw Dec 07 '17 at 06:58