环境变量可以全局设置,如下面的示例或每个阶段,正如你所料,每个阶段设置环境变量意味着它们仅适用于定义它们的阶段。
Jenkinsfile (Declarative Pipeline)
pipeline {agent anyenvironment {DISABLE_AUTH = 'true'DB_ENGINE = 'sqlite'}stages {stage('Build') {steps {sh 'printenv'}}}
}
脚本管道(高级):
Jenkinsfile (Scripted Pipeline)
node {withEnv(['DISABLE_AUTH=true','DB_ENGINE=sqlite']) {stage('Build') {sh 'printenv'}}
}
这种从Jenkinsfile
中定义环境变量的方法对于指示脚本(如Makefile
)以不同的方式配置构建或测试以在Jenkins中运行它们非常有用。
环境变量的另一个常见用途是在构建或测试脚本中设置或覆盖“虚拟”凭据,因为将凭据直接放入Jenkinsfile
(显然)是一个坏主意,Jenkins管道允许用户快速安全地访问Jenkinsfile
中的预定义凭据,而无需知道其值。