Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using env variables to set other variables in Jenkins pipeline as code

I cannot use environment variables set in previous blocks in access stage below.

pipeline{
agent any
stages{

      stage("set env variable"){

      steps{
           script{
             env.city = "Houston"
             }
          }
       } 
     }
     stage("access"){
     steps{
           sh """
              set brf = ${env.city}
              echo $brf

              """

         }

     }



  } 
  }

ERROR: groovy.lang.MissingPropertyException: No such property: brf for class: groovy.lang.Binding

What is an easier way to use jenkins declarative pipeline env variables ?

like image 642
Varunkumar Manohar Avatar asked Dec 27 '17 22:12

Varunkumar Manohar


People also ask

How does Jenkins pipeline use an environment variable?

In declarative pipeline syntax, you do this in an environment block in the pipeline definition (Jenkinsfile). You can do this: at the top level, to define environment variables that will be shared across all pipeline stages. at the stage level, if you want to define environment variables local to a stage.

How do you set global variables in Jenkins?

We can set global properties by navigating to “Manage Jenkins -> Configure System -> Global properties option”.


1 Answers

I cannot use environment variables set in previous blocks in access stage below.

If you look closely at the error, you can see Jenkins is actually unable to access brf, not env.city.

The issue here is caused by the way Jenkins interprets $var inside sh block:

  • if you use "double quotes", $var in sh "... $var ..." will be interpreted as Jenkins variable;
  • if you use 'single quotes', $var in sh '... $var ...' will be interpreted as shell variable.

Since the sh code in your script is wrapped in "double quotes", $brf is considered to be a Jenkins variable, while there is no such variable defined, therefore the error occurs.

To use shell variable inside double-quoted block add \ before $:

sh "echo \$var"

works the same way as

sh 'echo $var'

This should fix your pipeline script:

pipeline{
    agent any
    stages{
        stage("set env variable"){
            steps{
                script{
                    env.city = "Houston"
                }
            }
        }
        stage("access"){
            steps{
                sh """
                    brf=${env.city}
                    echo \$brf
                """
            }
        }
    }
}

Output from the pipeline:

[test] Running shell script
+ brf=Houston
+ echo Houston
Houston
like image 141
honorius Avatar answered Oct 04 '22 21:10

honorius