Jenkins Declarative Pipeline detect first run and fail when choice parameters present

Viewed 682

I often write Declarative Pipeline jobs where I setup parameters such as "choice". The first time I run the job, it blindly executes using the first value in the list. I don't want that to happen. I want to detect this case and not continue the job if a user didn't select a real value.

I thought about using "SELECT_VALUE" as the first item in the list and then fail the job if that is the value. I know I can use a 'when' condition on each stage, but I'd rather not have to copy that expression to each stage in the pipeline. I'd like to fail the whole job with one check up front.

I don't like the UI for 'input' tasks because the controls are hidden until you hover over a running stage.

What is the best way to validate arguments with a Declarative Pipeline? Is there a better way to detect when the job is run for the first time and stop?

1 Answers

I've been trying to figure this out myself and it looks like the pipeline runs with a fully populated parameters list.

So, the answer to your choice option is to make the first item a value like "please select option" and have your code use when to check that

For example

def paramset = true
pipeline {
  parameters {
    choice(choices: ['select','test','proof', 'prod'], name: 'ENVI')
  }
  stages {
     stage ('check') {
       when { expression { return params.choice.ENVI == 'select' }
       steps {
         script {
           echo "Missing parameters"
           paramset = false
         }
       }
     }
     stage ('step 1') {
       when { expression { return paramset }
       steps {
         script {
           echo "Doing step 1"
         }
       }
     }
     stage ('step 2') {
       when { expression { return paramset }
       steps {
         script {
           echo "Doing step 2"
         }
       }
     }
     stage ('step 3') {
       when { expression { return paramset }
       steps {
         script {
           echo "Doing step 3"
         }
       }
     }
  }      
}
Related