Home > database >  Jenkins Declarative Pipeline - Dynamic Environment Variable Based On Git Branch
Jenkins Declarative Pipeline - Dynamic Environment Variable Based On Git Branch

Time:11-04

I have a multi-branch Jenkins pipeline which is working fine. Now, I'm trying to optimize it. I have the following step:

`

stage('Migration-Dev') {
      environment {
        ENVIRONMENT = 'development'
      }
      when {
        anyOf {
          branch 'development';
          branch 'staging';          
          branch 'production';
         }
      }

      steps {
        echo "Installing the NodeJS dependencies..."
        sh 'npm ci'
        echo "Performing some more tasks"
        sh 'do somethingelse
       }
       }

`

Every git branch mentioned in the above step requires its unique ENVIRONMENT value to execute some specific actions.

Is it possible to dynamically create the ENVIRONMENT value name depending on the git branch instead of hard coding it? Something like if the branch is staging, then the ENVIRONMENT=release?

I would greatly appreciate any help.

CodePudding user response:

For sure, please have a look at this answer

What I have for example in my pipeline:

    environment {
        APIGEE_ORGANIZATION = "companyName"
        }

    stages {

        stage('Setup') {
                steps {
                    echo 'Getting Proxies source from Gitea'

                    script
                        {
                                if (env.BRANCH_NAME == 'qas') {
                                    echo 'Deployment to qas'
                                    env.APIGEE_ENVIRONMENT = 'qas'
                                }
                                if (env.BRANCH_NAME == 'sandbox'){
                                    env.APIGEE_ENVIRONMENT = 'sandbox'
                                    echo 'Deployment to sandbox'
                                }
                                if (env.BRANCH_NAME == 'main'){
                                    env.APIGEE_ENVIRONMENT = 'prod'
                                    echo 'Deployment to prod'
                                }
                         }
  • Related