HiveBrain v1.2.0
Get Started
← Back to all entries
patterngitMinor

JenkinsFile to get git branch name

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
jenkinsfilegetnamegitbranch

Problem

I want to get git current checkout BRANCH NAME in my Jenkins file here is the code snippet...
Here I am trying to push a file to my current branch
I have tried many things could not find it...

stage('Push yaml file to bitbucket'){
  steps{
    withCredentials([usernamePassword(credentialsId: '8e2ca0a6-2dc5-4f89-b76a-03076d6b0843', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
      sh '''
        echo '#!/bin/sh' > /home/jenkins/git_askpass.sh
        echo "exec echo \"${GIT_PASSWORD}\"" > /home/jenkins/git_askpass.sh
        chmod 775 /home/jenkins/git_askpass.sh
        echo "user: ${GIT_USERNAME}"
        GIT_ASKPASS=/home/jenkins/git_askpass.sh
        export GIT_ASKPASS
        cat /home/jenkins/git_askpass.sh
        pwd
        git status
        git checkout feature/OSCCX-44(here I want branch name )
        git config --global user.email "xyz.com"
        git config --global user.name "xyz"
        git add yaml_dev/04-idm-frontend-depl.yaml                
        git commit -m "jenkins commit"
        git push https://${GIT_USERNAME}@bitbucket/repository '''
    }
  }
}

Solution

If you check the Git plugin documentation, you can see that there is a GIT_BRANCH environment variable that you can use in your pipeline.

GIT_BRANCH - Name of the remote repository (defaults to origin),
             followed by name of the branch currently being used,
             e.g. "origin/master" or "origin/foo"


So, in your pipeline:

stage('Push to Bitbucket') {
steps {
withCredentials([usernamePassword(credentialsId: '8e2ca0a6-2dc5-4f89-b76a-03076d6b0843',
passwordVariable: 'GIT_PASSWORD',
usernameVariable: 'GIT_USERNAME')]) {
sh '''
# Content omitted
git checkout ${GIT_BRANCH}
# Content omitted
'''
}
}
}

Code Snippets

GIT_BRANCH - Name of the remote repository (defaults to origin),
             followed by name of the branch currently being used,
             e.g. "origin/master" or "origin/foo"

Context

StackExchange DevOps Q#9560, answer score: 2

Revisions (0)

No revisions yet.