首页 > 解决方案 > 如何在詹金斯管道的触发器部分使用环境变量?

问题描述

读取节点标签和 triggerConfigURL 的属性文件,节点标签有效,但我无法从环境读取和设置 triggerConfigURL。

def propFile = "hello/world.txt" //This is present in workspace, and it works.
pipeline {
    environment {
        nodeProp = readProperties file: "${propFile}"
        nodeLabel = "$nodeProp.NODE_LABEL"
        dtcPath = "$nodeProp.DTC"
    }
    agent { label env.nodeLabel } // this works!! sets NODE_LABEL value from the properties file.
    triggers {
         gerrit dynamicTriggerConfiguration: 'true',
                triggerConfigURL: env.dtcPath, // THIS DON'T WORK, tried "${env.dtcPath}" and few other notations too.
                serverName: 'my-gerrit-server',
                triggerOnEvents: [commentAddedContains('^fooBar$')]
    }
    stages {
        stage('Print Env') {
            steps {
                script {
                    sh 'env' // This prints "dtcPath=https://path/of/the/dtc/file", so the dtcPath env is set.
                }
            }
        }

运行作业后,配置如下:

在此处输入图像描述

标签: jenkinsjenkins-pipelinejenkins-groovyjenkins-job-dsl

解决方案


envandtriggers子句中,Jenkins 一个接一个地运行,看起来您已经通过实验证明了triggers首先运行和env第二个运行。它看起来也像是agent在追赶env

虽然我不知道程序员为什么做出这个具体决定,但我认为您处于一种先有鸡还是先有蛋的问题中,您想使用文件定义管道但只能在管道一次读取文件已定义并正在运行。

话虽如此,以下可能有效:

def propFile = "hello/world.txt"
def nodeProp = null

node {
    nodeProp = readProperties file: propFile
}

pipeline {
    environment {
        nodeLabel = nodeProp.NODE_LABEL
        dtcPath = nodeProp.DTC
    }
    agent { label env.nodeLabel } 
    triggers {
         gerrit dynamicTriggerConfiguration: 'true',
                triggerConfigURL: nodeProp.DTC, 
//etc.

推荐阅读