5

I'm trying to set an environment variable in a Jenkins pipeline job based on a parameter passed into the job; this way I can use the environment variable in every stage of the pipeline that requires it. I tried using a switch statement in the environment block:

parameters { choice(name: 'ENVIRONMENT', choices: 'dev\nst\nprod', description: 'Environment') } environment { script { switch(env.ENVIRONMENT) { case 'dev': BRANCH = master break case 'st': BRANCH = 2020Q1 break case 'prod': BRANCH = 2019Q4 break } } } 

However this didn't work, the job tried to evaluate all the lines before the equals sign as the KEY name:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 9: "script { switch(env.ENVIRONMENT) { case 'dev': BRANCH" is not a valid identifier and cannot be used for an environment variable. Identifiers must start with a letter or underscore and can contain only letters, numbers or underscores. @ line 9, column 7. script { 

How do I get this to work?

3
  • Your ENVIRONMENT value is in the params map and not the env map at that point. Commented Feb 5, 2020 at 15:38
  • @MattSchuchard you're right the statement should be switch(params.ENVIRONMENT) Commented Feb 10, 2020 at 23:11
  • You may consider using Active Choices plugin plugins.jenkins.io/uno-choice This plugin allows to set build parameters depending on other parameters. Commented Feb 21, 2023 at 15:53

1 Answer 1

10

There are few ways to achieve this. here is a one of them:

parameters { choice(name: 'ENVIRONMENT', choices: 'dev\nst\nprod', description: 'Environment') } stages(){ stage("some stage"){ steps { script{ switch(env.ENVIRONMENT) { case 'dev': env.BRANCH = "master" break case 'st': env.BRANCH = "2020Q1" break case 'prod': env.BRANCH = "2019Q4" break } withEnv(["BRANCH=${env.BRANCH}"]) { ................................... ................................... ................................... } } } } } 
Sign up to request clarification or add additional context in comments.

2 Comments

after the switch statement the BRANCH variable is available in the environment for this and all stages, rendering the withEnv section unnecessary.
@matus correct since it's setting an env variable that automatically makes it available in all stages, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.