Jenkins 声明式管道中的条件环境变量 [英] Conditional environment variables in Jenkins Declarative Pipeline

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

问题描述

我正在尝试获得如下所示的声明性管道:

I'm trying to get a declarative pipeline that looks like this:

pipeline {
    environment {
        ENV1 = 'default'
        ENV2 = 'default also'
    }
}

关键是,我希望能够根据任意条件覆盖 ENV1ENV2 的值.我目前的需要只是基于分支,但我可以想象更复杂的条件.

The catch is, I'd like to be able to override the values of ENV1 or ENV2 based on an arbitrary condition. My current need is just to base it off the branch but I could imagine more complicated conditions.

有什么健全的方法来实现这个吗?我在网上看到了一些类似的例子:

Is there any sane way to implement this? I've seen some examples online that do something like:

stages {
    stage('Set environment') {
        steps {
            script {
                ENV1 = 'new1'
            }
        }
    }
}

但我认为这并没有设置实际的环境变量,而是设置了一个覆盖以后对 ENV1 的调用的局部变量.问题是,我需要nodejs脚本读取这些环境变量,而且需要是真机环境变量.

But I believe this isn't setting the actually environment variable, so much as it is setting a local variable which is overriding later calls to ENV1. The problem is, I need these environment variables read by a nodejs script, and those need to be real machine environment variables.

有没有办法在 jenkinsfile 中将环境变量设置为动态的?

Is there any way to set environment variables to be dynamic in a jenkinsfile?

推荐答案

使用 withEnv 动态设置环境变量以用于管道的某个部分(例如,在运行节点脚本时).像这样(用你的节点脚本替换 sh 步骤的内容):

use withEnv to set environment variables dynamically for use in a certain part of your pipeline (when running your node script, for example). like this (replace the contents of an sh step with your node script):

pipeline {
    agent { label 'docker' }
    environment {
        ENV1 = 'default'
    }
    stages {
        stage('Set environment') {
            steps {
                sh "echo $ENV1" // prints default
                // override with hardcoded value
                withEnv(['ENV1=newvalue']) {
                    sh "echo $ENV1" // prints newvalue
                }
                // override with variable
                script {
                    def newEnv1 = 'new1'
                    withEnv(['ENV1=' + newEnv1]) {
                        sh "echo $ENV1" // prints new1
                    }
                }
            }
        }
    }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆