How to get latest build number from another job in jenkins pipeline - jenkins

I am using jenkins pipeline 2.0, and I would like to get another job's latest successful build number.
What's the pipeline syntax to use?

You can get it this way
def buildNumber = Jenkins.instance.getItem('jobName').lastSuccessfulBuild.number
If you get a RejectedAccessException you will have to approve those methods, see In-process Script Approval

To add to Vitalii's answer, this is in case you're using Multibranch Pipeline Plugin:
def buildNumber = Jenkins.instance.getItem('jobName').getItem('branchName').lastSuccessfulBuild.number

It's so annoying to get approvals in enterprise environment(a lot of request and approvals)
So I am using following API way to get the latest build number.
import groovy.json.JsonSlurperClassic
httpRequest url: 'https://jenkinsurl.local/job/Build/api/json', outputFile: 'output.json'
def jsonFile = readFile(file: 'output.json')
def data = new JsonSlurperClassic().parseText(jsonFile)
latestBuildNumber = "${data.lastSuccessfulBuild.number}"

def build_job = build job: "Build"
build_job_number = build_job.getNumber()

Related

Jenkins and Nexus Repository Manager Choice Parameter

I know there is a Nexus Platform plugin https://plugins.jenkins.io/nexus-jenkins-plugin/ in Jenkins but I am not sure if the below is possible any advise or suggestions would be appreciated.
In Jenkins you have Git choice parameter this allows you to build specific tags / branches within your job is there something similar for Sonatype Nexus? We have an internal nexus where we upload and tag docker images.
I currently have a Jenkins job I have to manually type in the image version.
Is there a way in Jenkins to get a choice parameter where i can query all the tags in nexus.
So for example I can run the command - > docker pull internal/application/service:0.0.1
So the developers would upload a new version for example 0.0.2
From Jenkins I would like to display a list of 0.0.1 or 0.0.2 for the support team to build.
Not sure if this is currently possible ?
Update 2020/07/15
I have read up on the active choice paramater plugin. This allows you to execute a groovy script.
So i created the below
import groovy.json.JsonSlurper
// GET
try {
def get = new URL("http://internalserver:8081/service/rest/v1/search?repository=docker-internal&name=application/service/moo").openConnection();
def getRC = get.getResponseCode();
//println(getRC);
if (getRC.equals(200)) {
//println(get.getInputStream().getText());
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(get.getInputStream().getText())
tags = parsedJson.items.version
//println(tags)
def sorted_tags = []
sorted_tags.push(tags)
println(sorted_tags)
}
}catch(Exception e){
println(e)
}
This code does print out the tags if i run it from my IDE but if i add it to the active choice plugin my drop down menu is blank ?
Ok i got it to work Jenkins combo box requires a return type.
So if anyone ever wants to do something similar the below worked for me.
<code>
import groovy.json.JsonSlurper
try {
def get = new URL("http://yourinternalnexusurl:8018/applicacation/v1...etc").openConnection();
def getRC = get.getResponseCode();
if (getRC.equals(200)) {
def nexus_response = [:]
nexus_response = new JsonSlurper().parseText(get.getInputStream().getText())
def image_tag_list = []
for (tag in nexus_response.items.version){
image_tag_list.add(tag)
}
return image_tag_list.sort()
}
}catch(Exception e){
println(e)
}
</code>
The Maven Artifact ChoiceListProvider (Nexus) may satisfy your requirements.
With this extension its possible to use the Service API from a Maven Repositories like Nexus, Maven-Central or Artifactory to search for artifacts using groupId, artifactId and packaging.
This plugin will let the user choose a version from the available artifacts in the repository and will publish the URL as an environment variable. The Plugin will return the full URL of the choosen artifact, so that it will be available during the build, i.E. you can retrieve the artifact by using "wget"
Example
You might then have to parse (groovy ?) the resulting env variable to feed as your parameter.

how to get build number of other job in jenkins pipeine

I have created a pipeline where for build there is one job and for mail notification another job. I need to get the build job latest BUILD_NUMBER(either success or failure whatever) in mail notification job and i should publish the build job latest url as a mail notification regarding the buildstatus.
How could i achieve this?
I think there are multiple ways that you could achieve this. Let's call your 2 builds A (build) and B (mail notification).
Call B from A; pass whatever information you need in B as a parameter
You can use a combination of this script and the Job API.
For #2, I'm thinking you would have something like this in your B job:
def jobname = "<name of Job A>"
def job = Jenkins.instance.getItemByFullName(jobname)
def build = job.getLastBuild()

Access BUILD_NUMBER in Jenkins Promoted build plugin scripts

I am using Promoted Build plugin. And using some custom groovy scripts to validate the build! I wanted to access the value of BUILD_NUMBER from the groovy script. Can anyone suggest me how i can achieve this?
Another thing i am writing println statement in this groovy script but its no where getting logged. Any suggestion to debug the script flow how can i log the info ?
Thanks
If it's in runtime you can use:
def env = System.getenv()
//Print all the environment variables.
env.each{
println it
}
// You can also access the specific variable, say 'username', as show below
String user= env['USERNAME']
if it's in system groovy you can use:
// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable
//Get from Env
def stashServer= build.parent.builds[0].properties.get("envVars").find {key, value -> key == 'ANY_ENVIRONMENT_PARAMETER' }
//Get from Job Params
def jobParam= "jobParamName"
def resolver = build.buildVariableResolver
def jobParamValue= resolver.resolve(jobParam)
Any println is sending output to the standard output steam, try looking at the console log.
Good luck!

Parameters added to build in the fly not passed to downstream jobs

I have Job_1, and Job_2.
In Job_1,
Step 1: Execute system Groovy script
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
Step 2: Trigger/call builds on other projects
Projects to build: JOB_2
Add parameters: Current build parameters
Step 3:
Execute Windows batch command
echo arts = %ARTS%
In Job_2,
Step 1:
Execute Windows batch command
echo arts from Job_1 = %ARTS%
Build Job_1, it does print out:
arts = safsaf
build_2 was successfully triggered, and print out:
arts from Job_1 = (blank)
it appears that only parameters in Job_1 defined in the This build is parameterized section can be passed to the downstream projects.
is this the expected behavior? How can parameters added in the fly be passed along?
I tried and this works:
in Job_1,
define a string parameter "ARTS" in the This build is parameterized section,
and change Groovy script from
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
to
import hudson.model.*
def build = Thread.currentThread().executable
build.replaceAction(
new ParametersAction(
new StringParameterValue('ARTS', 'safsaf')))
to overwrite the value of "ARTS", instead of adding a new parameter.
Give Parameterized Trigger Plugin a try. My downstream job was kicked off by a post build step Trigger parameterized build on other projects with Current build parameter from the plugin instead of the regular downstream job. Anything defined in This build is parameterized in Job_2 would pick up parameters passed from Job_1.
I may not be using this absolutely correct and I think there is a limitation on what can be captured vs cannot, but so far this captures all desired parameter from Job_1 for me.

New job on Jenkins on creation of new branch in BitBucket

I have integrated my BitBucket to my Jenkins. Is there a way to trigger a new job creation in Jenkins when a new branch is created in BitBucket?. The job name should be same as the new branch created. Can I do it with scripts, or Jenkins CLI or using BitBucket API.
I am new to Jenkins, any help would be appreciated.
Sure. This could be done. I recommend you to look at Job DSL Plugin. This is really convenient plugin. Moreover you could also put your job scripts under version control system (VCS).
All scripting is done in Groovy language. Find example below:
def project = 'quidryan/aws-sdk-test'
def branchApi = new URL("https://api.github.com/repos/${project}/branches")
def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
def jobName = "${project}-${branchName}".replaceAll('/','-')
job(jobName) {
scm {
git("git://github.com/${project}.git", branchName)
}
steps {
maven("test -Dproject.name=${project}/${branchName}")
}
}
}
Also take a look at online job playground for this plugin - Jenkins Job DSL Playground.
It is just a recommendation where to look at. Probably you will have more concrete questions on this topic. But definitely take a look at this plugin.

Resources