简体   繁体   中英

How to add environment variables from the Code in Jenkins?

So basically the program requires an env variable which is read this way:

var a = java.lang.System.getenv('envVariable');

Now as I am using a Jenkins Pipeline, I was looking for a way to supply this env variable in the pipeline, but I didn't find a way. Is there a way to achieve this with Jenkins?

You should use the environment section to define environment variables. The scope depends on the level of environment . Please see the official documentation for further details: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables

Example:

pipeline {
    agent {
        label 'my_label'
    }
    // These are visible in all stages
    environment {
        MY_ENV_VAR = 'value_of_var'
        DEBUG = 'true'
    }
    stages {
        stage('Build') {
            // These are visible only in the current stage (Build)
            environment {
                STAGE_ENV = 'value_stage_env'
            }
            steps {
                echo "MY_ENV_VAR = ${MY_ENV_VAR}"
                echo "DEBUG = ${DEBUG}"
                echo "STAGE_ENV = ${STAGE_ENV}"
                sh 'printenv'
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM