Jenkins管道条件环境变量

Jenkins管道条件环境变量

本文介绍了Jenkins管道条件环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a set of static environmental variables in the environmental directive section of a declarative pipeline. These values are available to every stage in the pipeline.I want the values to change based on an arbitrary condition.Is there a way to do this?

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
        ...
     }
   }
 }

推荐答案

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

I would suggest you to create a stage "Environment" and declare your variable according to the condition you want, something like below:-

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
            ...
         }
       }
    }
    }
}

这篇关于Jenkins管道条件环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:44