SteelerKid
SteelerKid

Reputation: 304

How to configure Jenkinsfile to only run a specific stage when running a daily cron job?

I've set a cron job to run every night, however I only want it to run stage B within the Jenkinsfile not all of them.

pipeline {
    agent any
    triggers {
            cron('@midnight')
        }

    }
    stages {
        stage('A') {
            ...
        }
        stage('B'){
            when {
              allOf {
                expression { env.CHANGE_TARGET == "master" }
                branch "PR-*"
              }
            }

            steps {
                sh """
                echo 'running script'
                make run-script
                """
            }
        }
        stage('C') {
          ...
        }

Without removing the conditionals in Stage B, I can't seem to figure out how to specify the cron to explicitly only run Stage B of the Jenkinsfile - I need to run that makefile script only when those conditionals are met OR during the daily midnight cron job

Upvotes: 3

Views: 2696

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6824

You can achieve what you want with the Parameterized Scheduler Plugin which enables you to define cron triggers that trigger the job with a specific environment variable, you can then use this variable as a condition to determine which step to execute.
in your case you can use that environment variable in the when directive of each stage to determine if it should run or not according to the variable.
Something like:

pipeline {
    agent any
    parameters {
        booleanParam(name: 'MIDNIGHT_BUILD', defaultValue: 'true', description: 'Midnight build')
    }
    triggers {
        parameterizedCron('''
           0 * * * * %MIDNIGHT_BUILD=true
        ''')
    }
    stages {
        stage('A') {
            when {
                expression { !env.MIDNIGHT_BUILD }
            }
            steps {
               ...
            }
        }
        stage('B') {
            when {
                expression { env.MIDNIGHT_BUILD || env.CHANGE_TARGET == "master" }
            }

            steps {
                sh """
                echo 'running script'
                make run-script
                """
            }
        }
        stage('C') {
            when {
                expression { !env.MIDNIGHT_BUILD }
            }
            steps {
                ...
            }
        }
    }
}

Upvotes: 4

Related Questions