Search code examples
githubjenkins-pipelinegit-branchjenkins-declarative-pipeline

Extract branch name from Git in Jenkins declarative pipeline when using pipeline as code


I am working on a Jenkins declarative pipeline, the pipeline get's trigger whenever there is change in release branch. Release branches are named in this format : release/v1.0 , release/v2.0 etc.

We are using below Git PollSCM stage to checkout whenever a new release branch is created.

stage ('git checkout')
    {
        steps
        {
            checkout poll:true, scm: ([$class: 'GitSCM',
            branches: [[name: 'origin/release/*']],
            userRemoteConfigs: [[credentialsId: "${GIT_CREDENTIALS_ID}", url: "${GIT_URL}"]]
            ])
        }    
    }

I am facing a problem to get version number from the release branch i.e. if my current release branch is "release/v1.0" the I want to extract "v1.0" from the release name.

When I use echo "${env.BRANCH_NAME}" it returns the branch name of my "pipeline as code" repository not the one I mentioned in "git checkout" stage .


Solution

  • I am able to get current checkout branch name in declarative pipeline using below code.

    stage ('git checkout')

    {
        steps
        {
            script
            {
             def scmVars = checkout poll:true, scm: ([$class: 'GitSCM',
            branches: [[name: 'origin/release/*']],
            userRemoteConfigs: [[credentialsId: "${GIT_CREDENTIALS_ID}", url: "${GIT_URL}"]]
            ])
            def releaseName=scmVars.GIT_BRANCH
            
            }
        } 
    
    }