My Jenkins pipeline is as follow:
pipeline {
triggers {
cron('H */5 * * *')
}
stages {
stage('Foo') {
...
}
}
}
The repository is part of a Github Organization on Jenkins - every branch or PR pushed results in a Jenkins job being created for that branch or PR.
I would like the trigger to only be run on the "main" branch because we don't need all branches and PRs to be run on a cron schedule; we only need them to be run on new commits which they already do.
Is it possible?
CodePudding user response:
yes - it's possible. To schedule cron trigger only for a specific branch you can do it like this in your Jenkinsfile:
String cron_string = (scm.branches[0].name == "main") ? 'H */5 * * *' : ''
pipeline {
triggers {
cron(cron_string)
}
// whatever other code, options, stages etc. is in your pipeline ...
}
What it does:
- Initialize a variable based on a branch name. For
main
branch it sets requested cron configuration, otherwise there's no scheduling (empty string is set). - Use this variable within pipeline
Further comments:
- it's possible to use it also with
parameterizedCron
(in a case you'd want / need to). - you can use also some other variables for getting branch name, e.g:
env.BRANCH_NAME
instead ofscm.branches[0].name
. Whatever fits your needs... - This topic and solution is discussed also in Jenkins community: https://issues.jenkins.io/browse/JENKINS-42643?focusedCommentId=293221#comment-293221
- EDIT: actually a similar question that leads to the same configuration - here on Stack: "Build Periodically" with a Multi-branch Pipeline in Jenkins
CodePudding user response:
You can simply add a when condition to your pipeline.
when { branch 'main' }