10raw
10raw

Reputation: 574

cannot print a defined environment variable inside powershell step in jenkinsfile

I am having trouble accessing the environment variable that I defined in Jenkinsfile ( Groovy ). My situation is that I can access the variable in any step outside the powershell ''' ''' but when I try to access it inside the powershell then it gives null value.



pipeline {
     environment {
        APP_BUILD = ''
        BUILD_NUM = ''
        APP_NAME = ''

    }
     agent {
        label 'test'
    }
    stages {
        stage('set env Variables ') {
             steps{
             script {

       APP_BUILD  = "name" 

       echo APP_BUILD
       //prints name which is expected and fine 
       powershell '''
       echo $env:APP_BUILD // does ot print anything
       echo $env:BUILDNUMBER // prints the build number 

       '''
             }
           }
        }
    }
}    

I tried to search for an solution where they say that if I use powershell """ """ , it might work but then I cannot assign it to other variable as in code below

pipeline {
     environment {
        APP_BUILD = ''
        BUILD_NUM = ''
        APP_NAME = ''

    }
     agent {
        label 'test'
    }
    stages {
        stage('set env Variables ') {
             steps{
             script {

       APP_BUILD  = "name" 

       echo APP_BUILD
       //prints name which is expected and fine 
       powershell """
       echo ${env:APP_BUILD} // prints output as expected 
       echo $env:BUILDNUMBER // prints the build number 
$build=${env:APP_BUILD} // gives an error saying groovy.lang.MissingPropertyException: No such property: build for class: groovy.lang.Binding 

       """
             }
           }
        }
    }
}    

then it echo the output but everytime I try to assign the environment variable to another local variable then it gives error which says groovy.lang.MissingPropertyException: No such property: build for class: groovy.lang.Binding

Please let me know if anyone has faced similar situations and solved it.

Upvotes: 1

Views: 941

Answers (1)

zett42
zett42

Reputation: 27796

You have to escape the '$' character when referring to PS variables, otherwise Groovy will try to interpolate:

powershell """
   echo "$APP_BUILD"     # it's simpler to let Groovy interpolate
   echo "$BUILDNUMBER"   # it's simpler to let Groovy interpolate
   \$build="$APP_BUILD"  # need to escape '$' when referring to PS variable
   """

Upvotes: 1

Related Questions