[英]Jenkins Pipeline: Set environment variable based on parameter
I'm trying to set an environment variable in a Jenkins pipeline job based on a parameter passed into the job;我正在尝试根据传递给作业的参数在 Jenkins 管道作业中设置环境变量; this way I can use the environment variable in every stage of the pipeline that requires it.这样我就可以在需要它的管道的每个阶段使用环境变量。 I tried using a switch statement in the environment block:我尝试在环境块中使用 switch 语句:
parameters {
choice(name: 'ENVIRONMENT', choices: 'dev\nst\nprod', description: 'Environment')
}
environment {
script {
switch(env.ENVIRONMENT) {
case 'dev':
BRANCH = master
break
case 'st':
BRANCH = 2020Q1
break
case 'prod':
BRANCH = 2019Q4
break
}
}
}
However this didn't work, the job tried to evaluate all the lines before the equals sign as the KEY name:但是这不起作用,该作业尝试将等号之前的所有行评估为 KEY 名称:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 9: "script {
switch(env.ENVIRONMENT) {
case 'dev':
BRANCH" is not a valid identifier and cannot be used for an environment variable. Identifiers must start with a letter or underscore and can contain only letters, numbers or underscores. @ line 9, column 7.
script {
How do I get this to work?我如何让这个工作?
There are few ways to achieve this.有几种方法可以实现这一点。 here is a one of them:这是其中之一:
parameters {
choice(name: 'ENVIRONMENT', choices: 'dev\nst\nprod', description: 'Environment')
}
stages(){
stage("some stage"){
steps {
script{
switch(env.ENVIRONMENT) {
case 'dev':
env.BRANCH = "master"
break
case 'st':
env.BRANCH = "2020Q1"
break
case 'prod':
env.BRANCH = "2019Q4"
break
}
withEnv(["BRANCH=${env.BRANCH}"]) {
...................................
...................................
...................................
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.