Makers_F
Makers_F

Reputation: 3063

Jenkins Scripted Pipeline: different operations depending on which cron triggers

I have a scripted pipeline and I'd like to execute different operations:

I know I can define multiple triggers with

properties(
    pipelineTriggers([cron("0 12 * * *"), cron("* * * * 6")])
)

But I don't know how I can then define the job later

if (???) {
    sh "run complex task"
} else if (???) {
    sh "run tests"
}

How can I find out which of the cron rules triggered my task?

Upvotes: 1

Views: 2924

Answers (1)

Krzysztof Błażełek
Krzysztof Błażełek

Reputation: 893

I believe you can't get to the cron information during the build. TimerTriggerCause contains only information that the build was triggered by timer.

node {
    properties([
    pipelineTriggers([cron("* * * * *")])
])
   def timeTriggerCause = currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause)
   println timeTriggerCause?.getShortDescription()
}

Couple of solutions:

  • Check date during the build
  • Use multiple pipelines. You can separate all the logic into one pipeline with boolean parameter (i.e. RunComplexTask). Other pipelines (triggered by timer) would call this pipeline and pass proper value for boolean parameter.

EDIT: I've added example of multiple pipeline setup

PIPELINE_RUN_COMPLEX_TASK:

node {
    properties([pipelineTriggers([cron('* * * * 6')])])
    build job: 'PIPELINE_MAIN', parameters: [booleanParam(name: 'RunComplexTask', value: true)]
}

PIPELINE_RUN_TESTS:

node {
    properties([pipelineTriggers([cron('0 12 * * *')])])
    build job: 'PIPELINE_MAIN', parameters: [booleanParam(name: 'RunComplexTask', value: false)]
}

PIPELINE_MAIN:

if(RunComplexTask.toBoolean())
{
    echo "Running complex task"
}
else
{
    echo "Running tests"
}

Pipeline main has this boolean parameter I've mentioned.

Upvotes: 1

Related Questions