Home > database >  Jenkins variable defined inside global variable(env variable)
Jenkins variable defined inside global variable(env variable)

Time:11-04

I have defined an environment(global) variable in jenkins via configuration as

REPORT = "Test, ${CycleNumber},${JOB_NAME}"

I have 1 parameter defined in my pipeline called Cycle which has values new & update. Based on this cycle value CycleNumber should be updated and I tried it via groovy using script block in my pipeline as below

if(Cycle == "New")
    {
        CycleNumber = "12345"
    }
else if (Cycle == "Update")
    {
       CycleNumber = "7890"
    }

after this update if I do echo "${env.REPORT}" I get the value as "Test,,TestJob" where in the CycleNumber variable is not updated. Could you please let me know if there is a way to update this CycleNumber field ?

CodePudding user response:

Here is an answer with a workaround here: Updating environment global variable in Jenkins pipeline from the stage level - is it possible?

TLDR: You can't override a global environment variable that has been declared in environment(global), however you can use the withEnv() function to wrap your script block in your pipeline to reference the updated value, eg:

withEnv(['REPORT=...']) {
  // do something with updated env.REPORT
}

CodePudding user response:

Don't rely on Groovy's String interpolation to replace the CycleNumber. You can have your own placeholder(e.g: _CYCLE_NUMBER_) in the environment variable which you can replace later in your flow. Take a look at the following example.

pipeline {
  agent any 
  stages {
    stage("Test") {
      environment {
        REPORT = "Test, _CYCLE_NUMBER_,${JOB_NAME}"
      }

      steps {
        script {
            def Cycle = 'New'
            def CycleNumber = 'none'
            if(Cycle == "New"){
                    CycleNumber = "12345"
            } else if (Cycle == "Update") {
                   CycleNumber = "7890"
            }

            def newReport = "$REPORT".replace('_CYCLE_NUMBER_', CycleNumber)
            echo "$newReport" 
        }
      }
    }
  }
}

Also once you set the newReport variable, make sure you use the same variable. if you do "${env.REPORT}" you will always get the original value assigned the tne environment variable.

  • Related