'How do I skip a Jenkins stage after executing some of its steps (like the when directive)?

How do I skip a Jenkins stage partway through its execution? It would be like using when after some steps or in the middle of a step, once the skip condition has been determined. I'm aware that I could break stages/steps down further and use a global variable to achieve this, but there seems like there should be a simpler way.

The step should appear skipped, not failed or unstable.

stage('Builds') {
    failFast true
    parallel {
        stage('FlagA') {
            steps {
                BuildWithFlag("FlagA")
            }
        }
        stage('FlagB') {
            steps {
                BuildWithFlag("FlagB")
            }
        }
        ...

void BuildWithFlag(String flag) {
    skipCondition = false
    <setup-steps>
    if(skipCondition) {
        currentStage.result = '' // Doesn't work
        return
    }
    <build-steps>
}

Related:
Conditional step/stage in Jenkins pipeline
How to perform when..else in declarative pipeline
Jenkins Pipeline stage skip based on groovy variable defined in pipeline

All of these use when at the start of the stage. I need to mimic it partway through a step.



Solution 1:[1]

You want to set the stage to "NOT_BUILT". This is the status given to steps that are skipped using when.

E.g.

if(skipCondition) {
    catchError(buildResult: 'SUCCESS', stageResult: 'NOT_BUILT') {
        error "Skipping..." // Force an error that we will catch to set the stageResult
    }
    return
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1