0

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?

Pauline
  • 3,566
  • 8
  • 23
  • 39

2 Answers2

2

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:

  1. 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).
  2. Use this variable within pipeline

Further comments:

David-kn
  • 323
  • 2
  • 8
-1

You can simply add a when condition to your pipeline.

when { branch 'main' }
ycr
  • 12,828
  • 2
  • 25
  • 45
  • As per the documentation you have linked, this is a directive available only for `stage` directives. It will not work on other directives such as `triggers`. – Pauline Jan 03 '23 at 14:57
  • @Pauline Yes, the idea is that you start the Job and skip the stages if the branch is not main. I may have understood your question wrong. Do you want to skip the execution if the branch is not main or do you want to add the Cron trigger only to the Pipeline that's created for main? – ycr Jan 03 '23 at 18:24
  • i'm also struggling to understand also why the when condition is not an acceptable solution, instead of the complex trigger. as far as I understood... for example when { expression { env.branch == 'main' // or GIT_BRANCH if used from github api webhooks or BRANCH_NAME for multibranch pipelines } should do exactly what OP wants, no? at each push on github... it will trigger a build on the pipeline. Probably is it possible to add an expression within the when block? – aamdevsecops Jan 04 '23 at 22:16
  • When a pipeline starts - even if all the stages are skip - still use worker / slave / executors / etc. If you are in a model where executors are dynamically provisioned, this starts an executor for no good reason. With enough branches / PRs opened etc this is enough to either cost a lot , or lead to executor exhaustion. The ask is to not execute the pipeline at all, not to skip all stages as per a trigger. – Pauline Jan 05 '23 at 14:45