0

I have a multibranch pipeline job, that executes a declarative pipeline Jenkins file. In this declarative pipeline, I have 2 parameters, a choice param, and a string param. On the first run of a branch due to params not yet loaded from the Jenkins file(it has not run yet, and they have to be in the Jenkins file), the job fails with the error of not knowing my params. My question is: How can I run a stage only if I see that the Jenkins param was not initialized?

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
Alon Tsaraf
  • 97
  • 1
  • 11
  • If you're interested if it's the first build, try `env.BUILD_NUMBER`. Otherwise there are default values for both choice and string parameters. – MaratC Nov 22 '21 at 10:21
  • @MaratC Thanks for the reply. The reason I do not check the build number is because this solution is not robust enough for me. what do I mean? this issue repeat for example when changing a param name in the jenkinsfile, so it might be the build 20 of a job passed, after that I renamed the param and on build 21 it fails. – Alon Tsaraf Nov 22 '21 at 10:28

1 Answers1

1

I've solved it this way: add a 'default' value to your choice, and check on it in your stage with an expression. Could be done the same with the String param.

parameters {
    choice(choices: ['none', 'internal', 'alpha', 'beta'], description: 'Deploy app to selected track', name: 'DEPLOY_TRACK')
}

And then in your stage:

stage('Deploy') {
    when {
        // Only execute this stage when selected DEPLOY_TRACK is `internal`, `alpha` or `beta`
        expression {
            return params.DEPLOY_TRACK != 'none'
        }
    }
    ...
}
SvdTweel
  • 172
  • 1
  • 2
  • 11
  • Thanks for the reply, this solution does not work for me, because on first build on my branch, the user is unable to choose param value, and default value is not used as well because param is not initialized. – Alon Tsaraf Nov 22 '21 at 10:41
  • The first option in your option list should be the default value, even if the user does or cannot set one. See [this answer](https://stackoverflow.com/a/47873797/3850345) – SvdTweel Nov 22 '21 at 10:59
  • Yes I am aware that first value of choice parameter for example is the default option, and in some jobs it definately is the case. However some jobs of mine do not get that default value from param, and i get the error the the param is unknown. – Alon Tsaraf Nov 22 '21 at 14:30
  • Could you update your question and add your pipeline? – SvdTweel Nov 22 '21 at 14:47