Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition in Jenkins pipeline on the triggers directive

Jenkins has a nice relatively comprehensive documentation about Jenkinsfile syntax. But I still not find there an answer is it possible to do a flow control on the top level of pipeline? Literally include something if just in pipeline {} section (Declarative) like:

pipeline {
    if (bla == foo) {
        triggers {
            ...configuration
        }
} 

or

pipeline {
    triggers {
        if (bla == foo) {
            something...
        }
    }
} 

triggers section is a section which can be included only once and only in the pipeline section. But if statement has to be applied only in stage level seems.

Do anyone know how to conditionally include something in direcitves, such as, triggers, or conditionally include directives itself?

like image 318
Mikhail Politaev Avatar asked Apr 08 '20 17:04

Mikhail Politaev


People also ask

How do you trigger a Jenkins pipeline from another pipeline?

You can follow the below steps to trigger a Jenkins pipeline in another Jenkins pipeline. Select a job that triggers a remote one and then go to Job Configuration > Build section > Add Build Step > Trigger builds on remote/local projects option.

What directive do you use for a declarative pipeline?

The agent directive specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent directive is placed. The directive must be defined at the top-level inside the pipeline block, but stage-level usage is optional.


1 Answers

You can't use flow control in a pipeline outside of when and script, but you can call functions for things like trigger parameters:

pipeline {
    agent any
    triggers{ cron( getCronParams() ) }
    ...
}

def getCronParams() {
    if( someCondition ) {
        return 'H */4 * * 1-5'
    }
    else {
        return 'H/30 */2 * * *'
    } 
}

Another way is to generate your pipeline script dynamically using evaluate():

evaluate """
pipeline {
    agent any        
    ${getTriggers()}    
    ...
}
"""

String getTriggers() {
    if( someCondition ) {
        return "triggers{ cron('H */4 * * 1-5') }"
    }
    else {
        return "triggers{ pollSCM('H */4 * * 1-5') }"
    } 
}
like image 130
zett42 Avatar answered Oct 20 '22 19:10

zett42