简体   繁体   English

如何从 Jenkins 的代码中添加环境变量?

[英]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.现在,当我使用 Jenkins 管道时,我正在寻找一种在管道中提供此环境变量的方法,但我没有找到方法。 Is there a way to achieve this with Jenkins?有没有办法通过 Jenkins 实现这一目标?

You should use the environment section to define environment variables.您应该使用environment部分来定义环境变量。 The scope depends on the level of environment . scope 取决于environment等级。 Please see the official documentation for further details: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables更多详情请查看官方文档: 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'
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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