Jenkins build using variable ${GIT_BRANCH} as sonarqube parameter without "origin/"

git, jenkins, sonarqube

Solution

You could create a new variable and assign the value:

`echo ${GIT_BRANCH} | cut -d'/' -f 2-`

Afterwards, you will be able to use the new variable in the Jenkins Git Branch SonarQube parameter, by following the below steps.

Steps

In build section add an `Execute Shell` step with `command`:

echo NEW_VAR=`echo ${GIT_BRANCH} | cut -d'/' -f 2-` > newfile

Then add an `Inject an environment variable` step with `Properties File Path`:

newfile

In SonarQube configuration leave the `branch` field `empty` and add the following in the `Additional properties field`:

-Dsonar.branch=${NEW_VAR}

The above solution is not very clean but I've verified that it works

Problem

Large team with separate git branches per team and sonar as a code quality checker. The scm tool is set up to pick up every branch that corresponds to this name: `'feature-branch-*'` which works perfectly, for the maven build. I wanted to set up sonarqube so it would use a different branch for every actual git branch, but sonarqube does not allow wildcards. It does however allow variables so I tried `${GIT_BRANCH}`, but this variable holds: `'origin/feature-branch-214'`, which sonarqube does not recognise as a valid branch name. Sonarqube expects `'feature-branch-214'` So I need something to put there (in sonarqube branch) that does a substring of the `${GIT_BRANCH}` to exclude the `'origin/'` part.

Original source