Home > database >  Jenkins pipeline with a conditional trigger
Jenkins pipeline with a conditional trigger

Time:01-05

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:

  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:

CodePudding user response:

You can simply add a when condition to your pipeline.

when { branch 'main' }
  • Related