Get branch name in case of pull request jenkins multibranch pipeline - jenkins

I am using Jenkins multibranch pipeline pull request feature when i print env.BRANCH_NAME it prints PR-pullrequestnumber. instead of that i want to get branch name how could i get it ?

I was able to get the branch name from env.CHANGE_BRANCH in case of a pull request.

You will get the exact branch name after merging the code. It's just to differ

Related

how to trigger gitlab webhook on merge only

Thanks for any help in advance,
I currently have a Gitlab Webhook successfully triggering a Jenkins job on the 'merge request events' option:
enter image description here
However, this triggers the Jenkins job for each stage of the merge request,
so whenever a request is created, updated, merged and closed - the URL is triggered and the Job is run for each of these stages.
Is it possible to limit the Webhook to **only ** trigger on a merge approval (so when the merge button is pressed only).
enter image description here
the Webhook payload passes in each stage under the "action" tag, but only care about the "merged" action.
As for the creation, update or closure of the request, I dont need the job to run at these stages.
..
I have tried to resolve this at the Jenkins side - I'm using the Generic Webhook Trigger Plugin and i'm passing in the JSON payload for the trigger - so I can manipulate the job per "action" value being sent though.
However, this was insufficient as the Gitlab Webhook will always trigger from the Gitlab side per 'merge event', resulting in multiple calls to the Jenkins job.
I have found the answer,
this comes in the way of the Generic Webhook Trigger Plugin.
As I have pulled the 'action' variable from the Gitlab Webhook payload:
adding Json payload variable
I can now add this variable to the "Optional Filter" within the same Jenkins plugin:
use the variable as a filter with the relevant expression
here I can re-use the merge action variable and look for the passed in value of "merge".
Now my job will only run if this expression if found within the variable i am pulling though.
Also.. I can add multiple variables into the 'Optional Filter' and make them dependant on the expressions being passed in.

How to retrieve a name (not a pull request number!) of my GitHub branch in Jenkinsfile

I have the following problem.
I have a Jenkinsfile where I list the shared libraries I want to import in the following format:
#Library('my-shared-library1')
#Library('my-shared-library2#1.0')
#Library('my-shared-library3#my-branch-name')
I want to retrieve the name of the branches - in my case 1.0 and my-branch-name and store them in a separate variable. I tried to use the env.GIT_BRANCH and env.BRANCH_NAME methods for that, but they both return only the pull-request number of my pipeline (e.g., PR-316 or master) but not a specific name of my branch.
In other words, is there a way to check whether something follows the # sign in the library name and return it?
Thank you very much in advance.

Why does MERCURIAL_REVISION return the value NULL when I try accessing it on Jenkins

On Mercurial I've implemented a hook in my hgrc file that activates when some sort of change occurs in Jenkins(i.e tagging or committing). Here is my hook code:
curl -X POST http://tokenusername:115d59a462df750d4f12347975b3d691cf#127.0.0.1:8080/job/pipelinejob/buildWithParameters/mercurial/notifyCommit?url=http://127.0.0.1:85/hg/experimentrepoistory?token=1247
So there's no issue with my hook notifying Jenkins that a change has occurred and the pipeline executes but for some reason I am having trouble getting the commit id or any or the author name's who made the commit etc. I went to the script console in jenkins and wrote the following code in groovy to see if the changeset data from Mercurial transferred over to Jenkins. Also all the libraries are imported
def job = hudson.model.Hudson.instance.getItem("pipelinejob")
def builds = job.getBuilds()
def thisBuild = builds[0]
println('Lets test Mercurial fields ' + thisBuild.getEnvironment()['MERCURIAL_REVISION']) //Lets test Mercurial fields null
It makes me think that MERCURIAL_REVISION for some reason wasnt defined even though I provided a job that has the changeset info. I was reading this documentation https://javadoc.jenkins.io/plugin/mercurial/hudson/plugins/mercurial/MercurialChangeSet.html#MercurialChangeSet-- that lists a bunch of functions that have alot of functions like getCommitId() getNode() etc that gets the information that I need. Problem is I'm not entirely sure how to instantiate MercurialChangeSet with the jenkin jobs pipelinejob that in theory should have the Mercurial commitId information. Thats why I wanted to know if I perhaps missed something obvious regarding accessing MERCURIAL_REVISION
So I found out that I need to enable the Pipeline script from SCM and that I need to put the Jenkinsfile with the pipeline code inside my workspace directory in order to get the changeset information. I am not entirely sure why this works since I would think the Jenkinsfile needs to be in the repo directory of the SCM

Trigger Multibranch Job from another

I have a job in Jenkins and I need to trigger another one when it ends (if it ends right).
The second job is a multibranch, so I want to know if there's any way to, when triggering this job, pass the branch I want to. For example, if I start the first job in the branch develop, I need it to trigger the second one for the develop branch also.
Is there any way to achieve this?
Just think about the multibranch job being a folder containing the real jobs named after the available branches:
Using Pipeline Job
When using the pipeline build step you'll have to use something like:
build(job: 'JOB_NAME/BRANCH_NAME'). Of course you may use a variable to specify the branch name.
Using Freestyle Job
When triggering from a Freestyle job you most probably have to
Use the parameterized trigger plugin as the plain old downstream build plugin still has issues triggering pipeline jobs (at least the version we're using)
As job name use the same pattern as described above: JOB_NAME/BRANCH_NAME
Should be possible to use a job parameter to specify the branch name here. However I didn't give it a try, though.
Yes, you can call downstream job by adding post build step: Trigger/Call build on other projects(you may need to install "Parameterized Trigger Plugin"):
where in Parameters section you define vars for the downstream job associated with vars from current job.
Also multibranch_PARAM1 and *PARAM2 must be configured in the downstreamjob:
Sometimes you want to call one or more subordinate multibranch jobs and have them build all of their branches, not just one. A script can retrieve the branch names and build them.
Because the script calls the Jenkins API, it should be in a shared library to avoid sandbox restrictions. The script should clear non-serializable references before calling the build step.
Shared library script jenkins-lib/vars/mbhelper.groovy:
def callMultibranchJob(String name) {
def item = jenkins.model.Jenkins.get().getItemByFullName(name)
def jobNames = item.allJobs.collect {it.fullName}
item = null // CPS -- remove reference to non-serializable object
for (jobName in jobNames) {
build job: jobName
}
}
Pipeline:
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
library 'jenkins-lib'
mbhelper.callMultibranchJob 'multibranch-job-one'
mbhelper.callMultibranchJob 'multibranch-job-two'
}
}
}
}
}

How do I get the name of the pipeline from inside the jenkinsfile

env.JOB_NAME Is the pipeline name suffixed with the branch name.
So env.JOB_NAME will be <jenkins_pipeline_name>_<my_branch>
How can I just get the pipeline name and store it in a var in the environment{} block at the top of my jenkinsfile to use through the file?
I don't want to resort to scripted pipeline just the declarative.
#red888 pointed out the following answer that worked like magic for me. I am pointing it out in an actual answer because I almost missed it:
env.JOB_BASE_NAME
Credit to #red888 in the comment above. Send upvotes his/her way.
Since you are using the multibranch job, the env variable is returning the actual job name that it created out of the branch .i.e. _ .. So, without some mechanism to strip/sed out the branch name, i don't think there is an env variable for it in jenkins out-of-the-box.
You can check http://YOUR-JENKINS-SERVER.com/pipeline-syntax/globals#env and it'll get you
JOB_NAME
Name of the project of this build, such as "foo" or "foo/bar".
JOB_BASE_NAME
Short Name of the project of this build stripping off folder paths, such as "foo" for "bar/foo".
For a jenkins organization project with multiple branches and PRs, the JOB_NAME is actually YOUR_ORG_NAME/YOUR_REPO_NAME/YOUR_BRANCH_OR_PR_NAME, e.g. my-org/my-repo/PR-23, and the JOB_BASE_NAME is just PR-23. Just as Israel said, you can use env.JOB_NAME.tokenize('/') as String[] to get what you want.
If you want more fancy scripts in Jenkins, Groovy can be a good reference.
In jenkins pipeline
def allJob = env.JOB_NAME.tokenize('/') as String[];
def projectName = allJob[0];
env.JOB_NAME is the project name... There is no DOUBT
However, my issue with copyArtifact plugin. It said :
Unable to find project for artifact copy: YOUR_PROJECT_WITH_ARTIFACTS
This may be due to incorrect project name or permission settings;
At the end it is not "incorrect project name", and env.JOB_NAME must work.
However, the issue is permission settings which can be fixed generally by :
pipeline {
agent any
options {
copyArtifactPermission('*');
}
//..
}
Reference

Resources