How to set branch name in variable in Jenkins Pipeline job?
I have Jenins pipeline below which returns null in BRANCH_NAME
node{
def BRANCH_NAME = env.BRANCH_NAME
echo BRANCH_NAME
}
To get branch name through env.BRANCH_NAME, your pipeline need to be Multiple Branch Pipeline.
BRANCH_NAME
For a multibranch 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).
Related
I have a parameterized Jenkins pipeline build. One of the parameters (branch) is the branch to build. The pipeline file is stored in the branch.
In the Pipeline definition, when I use */${branch} as the branch to build in place of */main the ${branch} does not get replaced but shows up as a literal. If I hard code the branch it works as expected.
The ${branch} does get replaced as expected in the pipeline file. So the branch parameter is being set.
Is there a way to get the parameter value into the "Pipeline script from SCM" retrieval from git?
You can try another approach as following:
In pipeline configuration page, change pipeline from SCM to pipeline script
Put following pipeline script in input box
node('<Jenkins node label>') {
properties([
parameters([
// parameter for branch
])
])
git url: '', credentailId:'', branch: "${branch}"
load '<relative path to your Jenkinsfile>'
}
You can use the branch parameter, when you disable the "Lightweight Checkout".
See JENKINS-28447
how to get BRANCH_NAME in jenkins windows command?
I tried
echo BRANCH_NAME
echo %BRANCH_NAME%
echo env.BRANCH_NAME
but jenkins console print the string "BRANCH_NAME" not the value of branch name.
I need branch_name to create in IIS dynamic aplications based on branch name and create a folder with branc_name
After installing Pipeline Multibranch Plugin(https://wiki.jenkins.io/display/JENKINS/Pipeline+Multibranch+Plugin)
Use env.BRANCH_NAME or Just BRANCH_NAME
For other environment-variables go to (<%http://localhost:8080%>/env-vars.html)
I'm trying to write my first Jenkins shared library and I'm struggling with something basic - getting the branch name.
I could do:
sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
However, that requires a checkout. Would it be possible to get the branch name (for both multibranch and freestyle) pipeline projects? I know I'll be using git, but I would like to avoid doing a checkout (until it is necessary).
The GIT_BRANCH environment variable should give you what you want. It won't work in pipeline until Jenkins 2.60 and upgraded pipeline model definition plugin.
If you are using a pipeline job, you can
Capture object returned from scm checkout
Reference environment variable
pipeline {
// ...
stages {
stage('Setup') {
steps {
script {
// capture scm variables
def scmVars = checkout scm
String branch = scmVars.GIT_BRANCH
// or use the environment variable
branch = env.GIT_BRANCH
}
}
}
// ...
}
}
Environment variable reference.
I ended up using this:
env.CHANGE_BRANCH ?: env.GIT_BRANCH ?: scm.branches[0]?.name?.split('/')[1] ?: 'UNKNOWN'
However, this requires me to approve several things in In-Script Approvals page.
Now that the Multibranch Pipeline job type has matured, is there any reason to use the simple Pipeline job type any longer? Even if you only have one branch today, it's probably wise to account for the possibility of multiple branches in the future, so what would the motivation be to use the Pipeline job type for your Jenkins Pipeline vs. always using the Multibranch Pipeline job type, assuming you are storing your Jenkinsfile in SCM? Is there feature parity between the two job types now?
In my experience with multibranch pipelines, the ONLY downside is that you can't see the last success/failure/duration columns on the Jenkins main page. They just show "NA" on the Jenkins front page since it's technically a 'folder' of sub-jobs.
Other than that I can't think of any other "cons" to using multibranch.
I disagree with the other answer.... that case was that multibranch sends changes for "any" branch. That's not necessarily true. If a Jenkinsfile exists on a random feature branch, but that branch is not defined in the pipeline then you can just not do anything with it using typical if/else conditionals.
For example:
node {
checkout scm
def workspace = pwd()
if (env.BRANCH_NAME == 'master') {
stage ('Some Stage 1 for master') {
sh 'do something'
}
stage ('Another Stage for Master') {
sh 'do something else here'
}
}
else if (env.BRANCH_NAME == 'stage') {
stage ('Some stage branch step') {
sh 'do something'
}
stage ('Deploy to stage target') {
sh 'do something else'
}
}
else {
sh 'echo "Branch not applicable to Jenkins... do nothing"'
}
}
Multibranch Pipeline works well if your Jenkins job deals with a single git repository. On the other hand, the pipeline job can be repository-neutral and branch-neutral and very flexible when working with multiple git repositories with a single Jenkins job.
For example, assume you have artifact-1 from repo-1, artifact-2 from repo-2, and integration tests from repo-3. And artifact-2 depends on artifact-1. A Jenkins job has to build artifact-1, then build artifact-2, and finally run integration tests from repo-3. And assume your code change goes to a feature-1 branch of repo-1 and feature-1 branch for new tests in repo-3. In this case, the Jenkins job builds feature-1 for artifact-1, then uses 'dev' branch as default from repo-2 (if feature-1 is not detected in repo-2), and runs 'feature-1' from repo-3 for new integration tests. As you can see, the job works well with three git repositories. A repo-neutral/branch-neutral pipeline job is ideal in this setting.
In a CI/CD situation, it may not be desirable to send every branch to the target environment. Using pipeline and specifying a single branch would allow you to filter, and send only /master to Staging or Production environments. Multibranch would be useful for sending any change on any branch specifically to a test environment.
On the other hand, if the QA/AutomatedTesting process is thorough enough, the risk with sending any branch to Production could be acceptable.
If you are still developing your flow, the simple pipeline has the added advantage of supporting parameterized projects. This feature is useful for developing the declarative pipelines in the jenkins gui, using the parameter to control what branch/repository you are targeting.
I need to know which branch is being built in my Jenkins multibranch pipeline in order for it to run steps correctly.
We are using a gitflow pattern with dev, release, and master branches that all are used to create artifacts. The dev branch auto deploys, the other two do not. Also there are feature, bugfix and hotfix branches. These branches should be built, but not produce an artifact. They should just be used to inform the developer if there is a problem with their code.
In a standard build, I have access to the $GIT_BRANCH variable to know which branch is being built, but that variable isn't set in my multibranch pipeline. I have tried env.GIT_BRANCH too, and I tried to pass $GIT_BRANCH as a parameter to the build. Nothing seems to work. I assumed that since the build knows about the branch being built (I can see the branch name at the top of the console output) that there is something that I can use - I just can't find any reference to it.
The env.BRANCH_NAME variable contains the branch name.
As of Pipeline Groovy Plugin 2.18, you can also just use BRANCH_NAME
(env isn't required but still accepted.)
There is not a dedicated variable for this purpose yet (JENKINS-30252). In the meantime you can take advantage of the fact that the subproject name is taken from the branch name, and use
env.JOB_NAME.replaceFirst('.+/', '')
This has now been resolved, see Krzysztof KrasoĊ's answer.
There are 2 branches to consider in a Jenkins multibranch pipeline job:
The Jenkins job branch - env.BRANCH_NAME. This may have the same name as a git branch, but might also be called PR-123 or similar
The git branch - env.GIT_BRANCH. This is the actual branch name in git.
So a job might have BRANCH_NAME=PR-123 and GIT_BRANCH=my-scm-branch-name
Jenkins documentation has a list of all the env variable for your perusal here
Another way is using the git command to obtain the branch name on the current jenkins pipeline. For example, you can add the following snippet to print the branch name in your Jenkinsfile.
...
script {
def BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
echo ${BRANCH}
}
...
I found this stackoverflow post example useful: Git Variables in Jenkins Workflow plugin
sh '//...
git rev-parse --abbrev-ref HEAD > GIT_BRANCH'
git_branch = readFile('GIT_BRANCH').trim()
echo git_branch
//...
'