mspolitaev
mspolitaev

Reputation: 723

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?

Upvotes: 8

Views: 8764

Answers (3)

Michael Doubez
Michael Doubez

Reputation: 6863

I had the same kind of issue: cron() were triggered on tags, PRs and branches while I wanted to limit it to daily run on main branch.

Using properties, I was able to parameterize the triggers:

// triggers
def job_triggers = []
if(env.BRANCH_NAME == "master" || env.BRANCH_NAME == "main") {
   job_triggers << cron('H 2 * * 1-5')
}
properties([pipelineTriggers(job_triggers)])

Upvotes: 0

jakub gros
jakub gros

Reputation: 11

Inspired by zett42's answer, I created a conditional trigger with Gerrit trigger plugin. The trigger is disabled when the "isGerrit" variable is set to false. It seems that as of today, Jenkins doesn't allow "if" directives to surround the "trigger" declaration, so you have to tinker with its parameters in order to make it not work for specific cases.

triggers {
  gerrit customUrl: GERRIT_HOST,
  gerritProjects: !isGerrit ? [] : [[
    branches: [
      [compareType: 'PLAIN', pattern: 'master'],
      [compareType: 'PLAIN', pattern: 'database']
    ],
    compareType: 'PLAIN',
    disableStrictForbiddenFileVerification: false,
    pattern: 'myProject'
  ]],
  serverName: 'gerrit',
  triggerOnEvents: [patchsetCreated()]
}

Upvotes: 0

zett42
zett42

Reputation: 27756

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') }"
    } 
}

Upvotes: 15

Related Questions