Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally trigger Jenkins multibranch pipeline

I have a parameterized Jenkins multibranch pipeline using a GitHub repo as the source for a Jenkinsfile and some scripts. The pipeline is configured to trigger on webhooks for branches and pull requests but I also want a parameterized cron trigger only for the master branch, specifically every 4hours on weekdays.

I'm using declarative pipeline syntax but I'm willing to use scripted pipeline if necessary.

I'm using the parameterized scheduler plugin to achieve cron triggers with parameters.

This pipeline example captures what I am trying to achieve but is not supported:

pipeline {
  triggers {
    when { branch "master" }
    parameterizedCron('H */4 * * 1-5 % ABC=XYZ')
  }
  stages {
  // do something
  }
}

There is an open Jenkins issue for this feature: JENKINS-42643 but it doesn't seem to be in development.

like image 252
Zach Weg Avatar asked Jun 16 '18 06:06

Zach Weg


People also ask

How does Jenkins use Multibranch pipeline?

Head over to your Jenkins instance and create a new item. Enter a name for the job, and select the “Multibranch Pipeline” option at the end of the screen. Then, click on the OK button. In the next screen, go to the “Branch sources” tab, click on the “Add source” button, and choose “Git” from the dropdown menu.

How do you trigger the pipeline for periodically?

To force a pipeline to run even when there are no code changes, you can use the always keyword. Scheduled builds aren't supported in YAML syntax in this version of Azure DevOps Server. After you create your YAML build pipeline, you can use pipeline settings to specify a scheduled trigger.

What do Multibranch pipelines enable?

The Multibranch Pipeline project type enables you to implement different Jenkinsfiles for different branches of the same project. In a Multibranch Pipeline project, Jenkins automatically discovers, manages and executes Pipelines for branches which contain a Jenkinsfile in source control.


1 Answers

Using a ternary operator worked for my use case. Builds are only scheduled for the master branch:

pipeline {
  triggers {
    parameterizedCron(env.BRANCH_NAME == 'master' ? '''
# schedule every 4hours only on weekdays
H */4 * * 1-5 % ABC=XYZ''' : '')
  }
  parameters {
    string(name: 'ABC', defaultValue: 'DEF', description: 'test param')
  }
  stages {
    // do something
  }
} 
like image 131
Zach Weg Avatar answered Sep 16 '22 18:09

Zach Weg