Search code examples
linuxbashjenkinsgroovyjenkins-pipeline

how to assign a jenkins global environment variable from inside an sh script


I have a jenkins global environment variable assigned, is it possible to override it from inside the sh""" """ script?

pipeline {
    environment {
        MYIMAGE=""
    }
    stages {
        stage('CREATE IMAGE'){
            steps {
                script {
                    if ((BRANCH_NAME == "DEV" )) {
                        script {
                               sh """  
                               if [[ $BRANCH_NAME == "dev" ]]; then
                                   env.MYIMAGE="image1";
                               elif [[ $BRANCH_NAME == "TESTING" ]]; then
                                   env.MYIMAGE="image2";
                               else
                                   env.MYIMAGE="image3";
                               fi
                               echo ${env.MYIMAGE}
                               """
                            }
                        }
                    }
                }
            }
        }
    }

so I want to set the envrionment variable conditionally from inside the script, is this possible?


Solution

  • I think no way to do as you said.

    Firstly, the Jenkins pipeline global env allow you insert new environment, but overwrite existing environment.

    Secondly, the sh step can't evaluate Groovy expression within Bash.

    If you accept use general Groovy variable, but environment you can do as following:

    // declare MYIMAGE to be a global variable of your pipeline
    // then you can access it anywhere in your pipeline
    
    // Don't define MYIMAGE in environment{}
    def MYIMAGE = "<you can put default value here or give empty value>"
    
    pipeline {
       stages {
         stage {
            script {
              def cmd = '''
                 if [[ $BRANCH_NAME == "dev" ]]; then
                    IMAGE="image1"
                 elif [[ $BRANCH_NAME == "TESTING" ]]; then
                    IMAGE="image2"
                 ...
                 fi
                 echo ${IMAGE}
              '''
              MYIMAGE = sh(returnStdout: true, script: cmd).trim()
            }
         }
       }
    }