Declarative Jenkinsfile: different cron trigger per branch

59 views
Skip to first unread message

Amedee Van Gasse

unread,
Jul 9, 2019, 4:34:06 AM7/9/19
to Jenkins Users
I have a *declarative* Jenkinsfile.
I want to have a daily build of the develop branch.
I currently have the following trigger:

    triggers {
        cron(env.BRANCH_NAME == 'develop' ? '@midnight' : '')
    }

Now I also want to build the master branch. Not daily, but weekly.
I already know that I can have only one cron expression in triggers.

I know of one solution that works, and that I do not want to use: have a different cron expression committed to each branch.
I don't want that, because master branches from develop and then gets merged back into develop. Doing it that way, will cause merge conflicts that I don't want to deal with.

The other solution is to have a more complex cron expression in the trigger.
In pseudo code:

IF (env.BRANCH_NAME = 'develop')
THEN cron = '@midnight'
ELSE IF (env.BRANCH_NAME = 'master')
THEN cron = '@weekly'

I don't know how to construct the correct syntax for the cron expression. Is that Groovy? Linux shell? Something else?

If possible, then I would like to avoid "polluting" my declarative pipeline with script blocks (I don't even know if they are allowed inside triggers).

Amedee Van Gasse

unread,
Jul 9, 2019, 5:36:25 AM7/9/19
to Jenkins Users
To answer my own question:

#!/usr/bin/env groovy

def schedule = env.BRANCH_NAME.contains('master') ? '@weekly' : env.BRANCH_NAME == 'develop' ? '@midnight' : ''

pipeline {

triggers {
cron(schedule)
}

Worked for me.

Ivan Fernandez Calvo

unread,
Jul 13, 2019, 7:07:16 AM7/13/19
to Jenkins Users
Hi,

Every branch has its own Jenkinsfile, so you can have different configuration on every Jenkinsfile

Amedee Van Gasse

unread,
Jul 16, 2019, 9:37:21 AM7/16/19
to Jenkins Users


On Saturday, July 13, 2019 at 1:07:16 PM UTC+2, Ivan Fernandez Calvo wrote:
Hi,

Every branch has its own Jenkinsfile, so you can have different configuration on every Jenkinsfile

Hi Ivan,

Merge conflicts shall be avoided at all possible cost, therefor my previous solution shall be used, and your solution shall not be used. 
Reply all
Reply to author
Forward
0 new messages