How to set different environment variables in a Jenkinsfile depending on the Git branch

I want to use different variables based on the Git branch to avoid using separate Jenkinsfiles for different branches. However, it seems that Groovy syntax doesn’t work within the environment{} directive.

I tried something like this without success:

		
if (current_branch == 'development') { CONFIG = 100 } else if (current_branch == 'main') { CONFIG = 200 }

How do you avoid creating multiple Jenkinsfiles?

Daniel Meier

6 months ago

3 answers

197 views

Rating

43
Answer

Answers

Daniel Karlsson

6 months ago

2 comments

Rating

01

I usually add a preliminary stage to set environment variables based on the branch:

		
stage('Setup') { steps { script { if (env.BRANCH_NAME == 'development') { env.CONFIG = '100' } else if (env.BRANCH_NAME == 'main') { env.CONFIG = '200' } } } }

Reply

    Daniel Meier

    6 months ago

    Rating

    00

    Thank you very much!

    Reply

    Emma Johnson

    2 months ago

    Edited

    Rating

    00

    thx all

    Reply