user1513171
user1513171

Reputation: 1974

Jenkinsfile - How to make a cron trigger kick off only a specifc stage?

I have a Jenkinsfile with the following triggers:

  triggers {
  cron('0 * * * 1-5')
}

So it will trigger at the top of the hour, every hour, Monday through Friday.

In the Jenkinsfile I have a number of stages like:

stage('CI Build and push snapshot') {
    when {
      anyOf { branch 'PR-*';branch 'develop' }
    }
 .
 .
 .
  stage('Build Release') {
    when {
      branch 'master'
    }
 .
 .
 .
  stage('Integration Tests') {
    when {
       ? // not sure what goes here
     }

What I want to do is, when that trigger is kicked off, I only want the Integration Tests stage to run. How do I achieve this? I think with what I have now every stage is going to be run.

Thanks!

Upvotes: 2

Views: 5455

Answers (2)

user1513171
user1513171

Reputation: 1974

I was able to get it working using something like:

 stage('CI Build and push snapshot') {
    when {
      anyOf { branch 'PR-*';branch 'develop' }
      not {
        expression { return currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger$TimerTriggerCause) }
      }
    }

 stage('Integration Tests') {
    when {
       branch 'develop'
       expression { return currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger$TimerTriggerCause) }
     }

Upvotes: 5

Sam
Sam

Reputation: 2882

Note this is using shared library functions and scripted syntax (not declarative), you will need to use script {} blocks in order to implement.

For organisation purposes, I put this into its own function in a shared library file called jobCauses.groovy under /vars, you can keep it in-line if you like, or put it at the bottom of the Jenkinsfile etc.

/**
 * Checks if job cause is Cron
 *
 * @return boolean
 */
boolean hasTriggeredCause() {

    List jobCauses = currentBuild.rawBuild.getCauses().collect { it.getClass().getCanonicalName().tokenize('.').last() }

    return jobCauses.contains('TimerTriggerCause')
}

Then in your pipeline:

stage('Integration Tests') {
    script {
        if ( jobCauses.hasTriggeredCause() ) {
            //do the thing
        }
    }
}

Upvotes: 1

Related Questions