如何在詹金斯管道的触发器部分中使用环境变量?

时间:2020-05-22 14:43:06

标签: jenkins jenkins-pipeline jenkins-groovy jenkins-job-dsl

读取节点标签和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.
                }
            }
        }

运行作业后,配置如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

Jenkins在envtriggers子句中先运行,并且看来您已经通过实验证明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.