Jenkins管道条件环境变量

时间:2019-05-10 05:49:28

标签: jenkins groovy

我在声明性管道的environmental指令节中有一组静态环境变量。这些值可用于管道中的每个阶段。 我希望根据任意条件更改值。 有办法吗?

pipeline {
   agent any
   environment {
     if ${params.condition} {
     var1 = '123'
     var2 = abc
    } else {
     var1 = '456'
     var2 = def
     }
   }
   stages {
     stage('One') {
      steps {
        script {
        ...
        echo env.var1
        echo env.var2            
        ...
     }
    }
   }
  }
  stag('Two'){
   steps {
        script {
        ...
        echo env.var1
        echo env.var2
        ...
     }
   }
 }

2 个答案:

答案 0 :(得分:1)

我建议您创建一个“环境”阶段,并根据所需条件声明变量,如下所示:-

pipeline {
   agent any
   environment {
     // Declare variables which will remain same throughout the build
   }
   stages {
     stage('Environment') {
                agent  { node { label 'master' } }
                steps {
                    script {
                       //Write condiion for the variables which need to change
                       if ${params.condition} {
                                 env.var1 = '123'
                                 env.var2 = abc
                                } else {
                                 env.var1 = '456'
                                 env.var2 = def
                                 }
                        sh "printenv"
                    }
                }
            }
         stage('One') {
          steps {
            script {
            ...
            echo env.var1
            echo env.var2            
            ...
         }
        }
       }
      stage('Two'){
       steps {
            script {
            ...
            echo env.var1
            echo env.var2
            ...
         }
       }
    }
    }
}

答案 1 :(得分:1)

寻找同样的事情,我在nice answer中发现了other question

基本上是使用ternary conditional operator

pipeline {
    agent any
    environment {
        var1 = "${params.condition == true ? "123" : "456"}"
        var2 = "${params.condition == true ? abc : def}"
    }
}

注意:请记住,在您写问题(和我的回答)的方式中,数字是字符串,字母是变量。