How can I skip a stage if the agent is offline?

Viewed 671

In my pipeline, I have a stage that checks to see if a specific computer (node) is offline. If it is, I want to skip the next stage. However, the next stage is set to use the offline agent, so it doesn't seem to be able to check the When clause.

Here's a simplified version of my pipeline:

pipeline {
    agent none

    environment {
        CONTINUERUN = true
    }

    stages {
        stage('Check Should Run') {
            agent any
            steps {
                script {
                    CONTINUERUN = false
                }
            }
        }

        stage('Skip this stage') {
            agent {
                label 'offlineAgent'
            }
            when {
                expression {
                    CONTINUERUN
                }
            }
            steps {
                //Do stuff here
            }
        }
    }
}

When I run this, the build just hangs at the 'Skip this stage' stage. I'm assuming, because the agent is offline. How can I skip this stage, when the agent is known to be offline?

1 Answers

In order to evaluate expression before allocating agent, you need to add beforeAgent directive to the when block.

Relevant part of documentation:

Evaluating when before entering agent in a stage

By default, the when condition for a stage will be evaluated after entering the agent for that stage, if one is defined. However, this can be changed by specifying the beforeAgent option within the when block. If beforeAgent is set to true, the when condition will be evaluated first, and the agent will only be entered if the when condition evaluates to true.

Related