Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-job-dsl

How to use env variable inside triggers section in jenkins pipeline?


Reading the properties file for the node label and triggerConfigURL, node label works, but I couldn't read and set triggerConfigURL from environment.

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

After running the job, the configuration is as below:

enter image description here


Solution

  • Of the env and triggers clauses Jenkins runs one before the other, and it looks like you have experimentally proven that triggers run first and env second. It also looks like agent runs after env as well.

    While I don't know why the programmers have made this specific decision, I think you are in a kind of a chicken-and-egg problem, where you want to define the pipeline using a file but can only read the file once the pipeline is defined and running.

    Having said that, the following might work:

    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.