Managing Dynamic Environment Variables Across Stages in Jenkins Multibranch Pipeline

Managing Dynamic Environment Variables Across Stages in Jenkins Multibranch Pipeline


Table of contents


In Jenkins pipelines, we often need to handle dynamic environment variables that are influenced by the branch being built. This post will discuss how to set these variables dynamically and use them across different stages in a Jenkins Multibranch Pipeline.

Problem Statement

Let’s consider a scenario where we have a Jenkins Multibranch Pipeline building branches named dev, test, and prod. We need to set a specific environment variable, BASE_DIR, depending on the branch being built. For instance, if the dev branch is being built, BASE_DIR should be set to ${FE_BASE_DIR}/dev. Similarly, for test and prod, BASE_DIR should be ${FE_BASE_DIR}/test and ${FE_BASE_DIR}/prod, respectively.

Solution

A common approach is to use the withEnv step, which allows you to set environment variables for the duration of the block it encloses. However, variables set in withEnv are not global, and hence, they are not accessible in subsequent stages.

A more suitable approach for our scenario involves using the env global variable in a script block, which allows us to define global environment variables that are accessible in subsequent stages. Here’s how you can do it:

pipeline {
    agent any

    stages {
        stage('Set environment variables') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'dev') {
                        env.BASE_DIR = "${env.FE_BASE_DIR}/dev"
                    } else if (env.BRANCH_NAME == 'test') {
                        env.BASE_DIR = "${env.FE_BASE_DIR}/test"
                    } else if (env.BRANCH_NAME == 'prod') {
                        env.BASE_DIR = "${env.FE_BASE_DIR}/prod"
                    } else {
                        env.BASE_DIR = 'unknown'
                    }
                    echo "BASE_DIR is set to ${env.BASE_DIR}"
                }
            }
        }
        // Other stages can now access env.BASE_DIR
    }
}

In the above pipeline, we’re using a script block inside the steps of a stage to conditionally set the BASE_DIR environment variable. This variable is now globally accessible and can be used in any subsequent stages.

Conclusion

Jenkins Pipelines offer a great deal of flexibility when it comes to handling dynamic environment variables. By leveraging the env global variable, you can define environment variables that are accessible across different stages, making your pipelines more dynamic and adaptable to various scenarios.

© 2024 Virendra Giri