Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a declarative pipeline

I'm trying the new declarative pipeline syntax.

I wonder, how can I abort all the stages and steps of a pipeline, when for example a parameter has an invalid value.

I could add a when clause to every stage, but this isn't optimal for me. Is there a better way to do so?

like image 437
david.perez Avatar asked Nov 29 '25 11:11

david.perez


1 Answers

This should work fine with a when directive, if you make use of the error step.

For example, you could do an up-front check and abort the build if the given parameter value is not acceptable — preventing subsequent stages from running:

pipeline {
  agent any
  parameters {
    string(name: 'targetEnv',
           defaultValue: 'dev',
           description: 'Must be "dev", "qa", or "staging"')
  }
  stages {
    stage('Validate parameters') {
      when {
        expression {
          // Only run this stage if the targetEnv is invalid
          !['dev', 'qa', 'staging'].contains(params.targetEnv)
        }
      }
      steps {
        // Abort the build, skipping subsequent stages
        error("Invalid target environment: ${params.targetEnv}")
      }
    }
    stage('Checkout') {
      steps {
        echo 'Checking out source code...'
      }
    }
    stage('Build') {
      steps {
        echo 'Building...'
      }
    }
  }
}
like image 80
Christopher Orr Avatar answered Dec 02 '25 03:12

Christopher Orr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!