简体   繁体   中英

How to access the BRANCH_NAME variable within a Jenkins pipeline running on Windows?

I wrote a Jenkins pipeline which git clones a repository, builds feature branches code and if everything is finished successfully it should merge the branch to master.

here's the relevant code:

stage ('Merge to master') {
    if(currentBuild.result == 'SUCCESS') {
        bat """
            cd %workspace%
            echo "BRANCH_NAME: %BRANCH_NAME%"
            echo "Env.BRANCH_NAME: %env.BRANCH_NAME%
            git checkout master
            REM git merge %GIT_BRANCH%
        """
    }
}

The code which is responsible for the cloning:

stage ('Checkout SCM') { // This stage is responsible to clone the repository into Jenkins's workspace
            checkout([$class: 'GitSCM', branches: [[name: '*/feature/*']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '99f978af-XXXX-XXXX-8147-2cf8f69ef864', url: 'http://TFS_SERVER:8080/tfs/DefaultCollection/PC_International/_git/repo-name']]])
} 

My problem is that it seems like the BRANCH_NAME variable is not set, I've tried accessing it by %BRANCH_NAME% , %env.BRANCH_NAME% , %GIT_BRANCH% and %env.GIT_BRANCH% but to no avail.

In Jenkins build log, it looks like that:

C:\Program Files (x86)\Jenkins\workspace\Ensure>echo "BRANCH_NAME: " 
"BRANCH_NAME: "

C:\Program Files (x86)\Jenkins\workspace\Ensure>echo "Env.BRANCH_NAME:  
"Env.BRANCH_NAME: 

C:\Program Files (x86)\Jenkins\workspace\Ensure>echo "GIT_BRANCH: " 
"GIT_BRANCH: "

C:\Program Files (x86)\Jenkins\workspace\Ensure>echo "Env.GIT_BRANCH: env.GIT_BRANCH" 
"Env.GIT_BRANCH: env.GIT_BRANCH"

Any idea what I'm doing wrong?

You need to interpolate the string value using the Groovy placeholders ${}, ie ${env.BRANCH_NAME}

This will replace the variable with the string literal before the batch script is executed. The %% notation is for interpolating windows environment variables, but env.BRANCH_NAME is Jenkins environment variable not a windows environment variable.

This worked for me:

  1. "manage jenkins" -> "Configure System" ... scroll down to "Global Properties" and check the checkbox for "Environmental Variables".
  2. Add your variable (ie Name: MY_BRANCH, value: "*/master")
  3. Restart Jenkins
  4. Go to your build then you can use the variable in your build configs as ${MY_BRANCH}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM