Jenkins Pipeline:根据参数设置环境变量

时间:2020-02-05 01:50:49

标签: jenkins jenkins-pipeline jenkins-groovy

我正在尝试根据传递给作业的参数在Jenkins管道作业中设置环境变量;这样,我可以在需要它的管道的每个阶段中使用环境变量。我尝试在环境块中使用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        
    }
  }
}

但是这不起作用,该作业尝试评估等号之前的所有行作为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 {

如何使它工作?

1 个答案:

答案 0 :(得分:3)

有几种方法可以实现此目的。这是其中之一:

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}"]) {
                ...................................
                ...................................
                ...................................

           }
        }
     }
   }
}