Search code examples
jenkinsjenkins-declarative-pipeline

How to share environment variable value across different Jenkins Pipelines?


I have two Jenkins Pipelines :

  • Pipeline A : In a stage, I defined an environment variable called MAVEN_PROFILE (the user can choose a value from a list)
  • Pipeline B : I need to get the MAVEN_PROFILE environment variable value that was set in Pipeline A

I need two pipelines because I can't do it in a single Pipeline for process reason.

I saw there was some answers on how to share variable between stages within a single Pipeline but this not my case.

I want to share environment variable value between different Pipelines.

Pipeline A

pipeline {
 agent any
...
 stages {
    stage('Profile Selection'){
       steps {
         script {
             env.MAVEN_PROFILE = input message: 'Choose the profile :',
             parameters: [choice(name: 'MAVEN_PROFILE', 
            choices: 'all\nserver\nclient', description: 'Profiles')]
         }
       }
    }
 stage(...){
       steps {
         script {
           bat "mvn deploy -P ${env.MAVEN_PROFILE}"
         }
       }
    }
... other stages
  }
}

Pipeline B

pipeline {
 agent any
...
 stages {
... other stages
    stage(...){
       steps {
         script {
           bat "mvn release ... -P ${env.environmentVariableValueFromPipelineA}"
         }
       }
    }
  }
}


Solution

  • They're not running in the same environment, so they can't directly share environment variables. The easiest is probably to write these values to a file in the workspace in pipeline A, and read them back in in pipeline B. Something like this:

    Pipeline A:

    sh "echo ${MAVEN_PROFILE} > .MAVEN_PROFILE" 
    

    Pipeline B:

    def MAVEN_PROFILE = sh(script: 'cat .MAVEN_PROFILE', returnStdout: true).trim()