1

How can I set a new environment variable from within a Jenkinsfile using declarative pipeline?

I know that I can read environment variables using env like this one for example ${env.JOB_NAME}.

But how can I set a new environment variable which can be be used by my build script for example. I want to do something like below. Is this the correct way?

stage("build_my_code") {
    steps {
        sh 'MY_ENV_VAR="some_value"'
        sh './my_script.sh $MY_ENV_VAR'
    }
}
TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159
  • Do you want to set a new environment variable in `Jenkinsfile` and then use that variable in an other declarative pipeline script or use it in same `Jenkinsfile`? Have you looked at https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#withenv-set-environment-variables or https://www.jenkins.io/doc/book/pipeline/syntax/#environment ? – Melkjot Sep 08 '21 at 08:53
  • In the same pipeline, not in other pipeline. My build script needs an environment variable to be set. All I want to do is to set the environment variable in the `Jenkinsfile` before running my script. – TheWaterProgrammer Sep 08 '21 at 09:07
  • You want to set a Jenkins environment variable or bash environment variable? Can you provide the console ouput of your job? – Melkjot Sep 08 '21 at 10:09
  • I want to set a bash environment variable – TheWaterProgrammer Sep 08 '21 at 11:05
  • Have a look at https://stackoverflow.com/questions/40323490/passing-variable-to-bash-script-in-a-jenkins-pipeline-job and https://stackoverflow.com/questions/51407976/defining-a-variable-in-shell-script-portion-of-jenkins-pipeline – Melkjot Sep 08 '21 at 12:38

1 Answers1

3

You can use script step to run Groovy script in declarative pipeline, Then in script step to set environment by env.xxx=yyy

stage("build_my_code") {
    steps {
        script {
           // the MY_ENV_VAR environment variable should not exist, 
           // not allow to overwrite value of an existing environment variable.
           env.MY_ENV_VAR="some_value"
        }
        sh './my_script.sh $MY_ENV_VAR'
    }
}
yong
  • 13,357
  • 1
  • 16
  • 27