Reputation: 57
I'm new to Jenkins jobs and I can't seem to figure out how to use global environment variables. I need to find the branch name that my Jenkinsfile is in. I have only placed it in a feature branch because I'm still testing it out, and I have that feature branch specified in the config for the pipeline. Here's my code so far
pipeline {
agent any
options {
buildDiscarder(logRotator(numToKeepStr:'3'))
timeout(time: 30, unit: 'MINUTES')
}
tools {
maven 'Maven 3.3.9'
jdk 'JDK 1.8'
}
stages {
stage('Checkout') {
steps {
echo 'Checking out..'
checkout scm
echo "My branch is: ${env.BRANCH_NAME}"
}
}
stage('Build') {
steps {
echo 'Building..'
bat 'mvn clean verify -P!local'
}
}
stage('SonarQube analysis'){
steps{
echo 'Analysing...'
withSonarQubeEnv('SonarQube') {
bat 'mvn org.sonarsource.scanner.maven:sonar-maven plugin:3.2:sonar'
}
}
}
}
}
I've tried a lot of different things but I always end up getting null for ${env.BRANCH_NAME}
Upvotes: 2
Views: 3888
Reputation: 349
Please note that only when you run the pipeline code in MultiBranch Project you would be able to fetch the branch name environment variable. The documentation from Jenkins is as follows:
BRANCH_NAME For a multi branch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches; if corresponding to some kind of change request, the name is generally arbitrary (refer to CHANGE_ID and CHANGE_TARGET).
So, you can use the environment variable only in a MultiBranch Pipeline Project. you can retrieve it in multi branch project using the below variable: "${env.BRANCH_NAME}"
Upvotes: 4