10

I want to create a Jenkins (v2.126) Declarative syntax pipeline, which has stages with when() clauses checking the value of an environment variable. Specifically I want to set a Jenkins job parameter (so 'build with parameters', not pipeline parameters) and have this determine if a stage is executed.

I have stage code like this:

stage('plan') {
  when {
     environment name: ExecuteAction, value: 'plan'
  }
  steps {
     sh 'cd $dir && $tf plan'
  }
}

The parameter name is ExecuteAction. However, when ExecuteAction is set via a Job "Choice" parameter to: plan, this stage does not run. I can see the appropriate value is coming in via environment variable by adding this debug stage:

stage('debug') {
  steps {
     sh 'echo "ExecuteAction = $ExecuteAction"'
     sh 'env'
  }
}

And I get Console output like this:

[Pipeline] stage
[Pipeline] { (debug)
[Pipeline] sh
[workspace] Running shell script
+ echo 'ExecuteAction = plan'
ExecuteAction = plan
[Pipeline] sh
[workspace] Running shell script
+ env
...
ExecuteAction=plan
...

I am using the when declarative syntax from Jenkins book pipeline syntax, at about mid-page, under the when section, built-in conditions.

Jenkins is running on Gnu/Linux.

Any ideas what I might be doing wrong?

2 Answers 2

10

Duh! You need to quote the environment variable's name in the when clause.

stage('plan') {
  when {
     environment name: 'ExecuteAction', value: 'plan'
  }
  steps {
     sh 'cd $dir && $tf plan'
  }
}
Sign up to request clarification or add additional context in comments.

Comments

7

I believe you need to use params instead of environment. Try the following:

when {
     expression { params.ExecuteAction == 'plan' }
}

2 Comments

Yes, thanks. The original question was answered regarding use of environment variables. But a parameter should do the trick too.
Just to complete this conversation, @KevinBuchs's code works because params are also accessible as env vars. I personally find the syntax of the environment when-clause unintuitive, so it's nice to have two options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.