Home > database >  how to use environment variable in powershell block and groovy block in Jenkins Pipeline
how to use environment variable in powershell block and groovy block in Jenkins Pipeline

Time:04-06

I am trying to access a environment variable created and used that in powershell block and changed that value and want to access again in grovvy section? Is this feasible ?

pipeline {  
       //adding environment varialbe
        environment {
        var1 = "somvalue"
           }

       stage ('accessvariables'){
          steps{
               script{
                      powershell '''

                       write-host "Prining environment variable here $env:var1"                                                                                                                      
                       $env:var1 = "changedValue"

                       '''
                        echo "${env.var1}" //its printing orginal somevalue I want changed value               

                      }
                  }
              }      

      }

CodePudding user response:

https://www.jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#powershell-windows-powershell-script

pipeline {
    environment {
        var1 = "somvalue"
    }

    stage('accessvariables') {
        steps {
            script {
                env.var1 = powershell returnStdout: true, ''' write-host "changedValue" '''
                echo "${env.var1}"
            }
        }
    }
}

or you could use something like this to return multiple values

pipeline {
    environment {
        var1 = "somvalue"
    }

    stage('accessvariables') {
        steps {
            script {
                env.var1 = powershell returnStdout: true, ''' write-host "changedValue" '''
                echo "${env.var1}"
            }
            
            script {
                def newEnv = powershell returnStdout: true, '''
                    @{
                        var1 = $env:var1.ToUpper()
                        var2 = "hohoho"
                    } | ConvertTo-Json -Depth 10
                '''
                newEnv = readJSON text:newEnv
                env.putAll(newEnv)
                echo "${env.var1}"
                echo "${env.var2}"
            }
        }
    }
}
  • Related