Jenkins v2.289.3
I'm trying to implement the Active Choices plugin discussed in one of the answers in in How to get a parameter depend of other parameter in Hudson or Jenkins, but unsure how to implement my second script to get the value from the first parameter.
I have a MyFolder job folder with multi-pipeline job called Builders, with branches like master, release/*, feature/*. So the full name of the jobs in the folder will be MyFolder/Builders/release%2F1.0.0 for the release/1.0.0 job for example (%2F is the escape character for /).
I then created a second job in the same folder called DeployBranchVersion, whose goal is to execute deployment code that deploys a chosen branch and one its corresponding successful build numbers. I therefore need to pass 2 parameters to the deployment code, GIT_BRANCH and VERSION.
My first Active Choices parameter gets these branches using the following script, and assigns the choice to the GIT_BRANCH parameter.
Job name: MyFolder/DeployBranchVersion
Parameter name: GIT_BRANCH
Groovy script:
def gettags = "git ls-remote -h -t https://username:password#bitbucket.org/organization/myrepo.git".execute()
def branches = []
def t1 = []
gettags.text.eachLine {branches.add(it)}
for(i in branches)
t1.add(i.split()[1].replaceAll('\\^\\{\\}', '').replaceAll('refs/heads/', '').replaceAll('refs/tags/', ''))
t1 = t1.unique()
return t1
This returns a drop-down list of the branches in my repo, and the chosen one is assigned to the GIT_BRANCH parameter.
Now how do I setup the second Active Choices Reactive parameter to reference the above choice? I have the following Groovy code that works in a non-Active-Choice parameter setup. How can I modify it to work in this case? The BUILD_JOB_NAME needs to reference the GIT_BRANCH value from the first parameter?
import hudson.model.*
BUILD_JOB_NAME = "some_reference_to_GIT_BRANCH" // ??????????
def getJobs() {
def hi = Hudson.instance
return hi.getItems(Job)
}
def getBuildJob() {
def buildJob = null
def jobs = getJobs()
(jobs).each { job ->
if (job.fullName == BUILD_JOB_NAME) {
buildJob = job
}
}
return buildJob
}
def getAllBuildNumbers(Job job) {
def buildNumbers = []
(job.getBuilds()).each { build ->
def status = build.getBuildStatusSummary().message
if (status.contains("stable") || status.contains("normal")) {
buildNumbers.add("${build.displayName}")
}
}
return buildNumbers
}
def buildJob = getBuildJob()
return getAllBuildNumbers(buildJob)
I tried setting it this way to ho avail.
BUILD_JOB_NAME = "MyFolder/Builders/$GIT_BRANCH"
Turns out I was doing it correctly, I just had a buggy 2nd script. Here's the good one. I realized that GIT_BRANCH values had / in them so I had to replace them with the equivalent escape character %2F.
import hudson.model.*
BRANCH = GIT_BRANCH.replaceAll("/", "%2F")
BUILD_JOB_NAME = "MyFolder/Builders/$BRANCH"
def getJobs() {
def hi = Hudson.instance
return hi.getAllItems(Job.class)
}
def getBuildJob() {
def buildJob = null
def jobs = getJobs()
(jobs).each { job ->
if (job.fullName == BUILD_JOB_NAME) {
buildJob = job
}
}
return buildJob
}
def getAllBuildNumbers(Job job) {
def buildNumbers = []
(job.getBuilds()).each { build ->
def status = build.getBuildStatusSummary().message
if ((status.contains("stable") || status.contains("normal")) &&
build.displayName.contains("-")) {
buildNumbers.add(build.displayName)
}
}
return buildNumbers
}
def buildJob = getBuildJob()
return getAllBuildNumbers(buildJob)
I have the following code in a separate groovy file from my Jenkinsfile. It's supposed to cancel old build jobs once a new one is fired off. It also checks for different branch names.
#NonCPS
def cancelPreviousBuilds() {
def buildNumber = env.BUILD_NUMBER.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(env.JOB_NAME)
def currentBranch = env.BRANCH_NAME // Branch value of the current build
// Cancel old jobs that are from the same branch
for (def build : currentJob.builds) {
// parse out the branch name from each job
param = (build.getFullDisplayName().tokenize('ยป')[2]).tokenize(" ")[0]
if (build.isBuilding() && build.number < buildNumber && currentBranch == param) {
build.doStop()
}
}
}
However, my code is failing on
def buildNumber = env.BUILD_NUMBER.toInteger()
The error from Jenkins says:
java.lang.NullPointerException: Cannot invoke method toInteger() on null object
Can I not use toInteger() here? From echo'ing out buildNumber this is definitely pulling out the build number, so I am pretty sure it is not actually null.
You can convert it to integer using Integer.parseInt:
def buildNumber = Integer.parseInt(env.BUILD_NUMBER)
Adding snippet of code which I modified:
def currentJob = Jenkins.instance.getItemByFullName(env.JOB_NAME)
def buildNumber = Integer.parseInt(env.BUILD_NUMBER)
def jobBuilds = currentJob.getBuilds()
jobBuilds.each{ build ->
// Your condition goes here
if (build.number < buildNumber ){
build.doStop()
}
}
I have the following code to cancel a previous job build if a new one is started:
def cancelPreviousBuilds() {
def jobName = env.JOB_NAME
def buildNumber = env.BUILD_NUMBER.toInteger() /* Get job name */ def currentJob =
Jenkins.instance.getItemByFullName(jobName)
for (def build : currentJob.builds) {
if (build.isBuilding() && build.number.toInteger() != buildNumber) {
build.doStop()
}
}
}
However, I would like this to not cancel previous job builds if it's a different branch. For instance, if a job build on develop were kicked off and then another one on master, it would not cancel any job builds.
You can access the build parameters of each build and compare the relevant values.
You can use build.getAction(hudson.model.ParametersAction) to get the ParametersAction object from where you can search for parameters in the build object using the getParameter function.
Something like:
#NonCPS
def cancelPreviousBuilds() {
def buildNumber = env.BUILD_NUMBER.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(env.JOB_NAME)
def currentBranch = <BRANCH_PARAM_NAME> // Branch value of the current build
for (def build : currentJob.builds) {
def param = build.getAction(hudson.model.ParametersAction).getParameter('<BRANCH_PARAM_NAME>')
if (build.isBuilding() && build.number.toInteger() > buildNumber && currentBranch == param.value) {
build.doStop()
}
}
Another small thing, in the build number comparison it is better to use build.number.toInteger() > buildNumber then build.number.toInteger() != buildNumber to prevent the case in which old builds cancel new started builds, as you usually want each build to affect only previous ones.
I'm trying to make my build pipeline more useful and I need a way to terminate previous builds if they are not finished yet.
I have the next Job definition:
pipeline {
stages {
stage('A'){...}
stage('B'){...}
stage('C'){...}
}
}
And I need to terminate all previous builds if they are not in stage'C'.
I use Jenkins API to get previous builds for a particular job:
#NonCPS
def cancelPreviousBuilds() {
def buildNumber = env.BUILD_NUMBER.toInteger()
def currentJob = Jenkins.getInstance().getItemByFullName(env.JOB_NAME)
currentJob.builds
.find{ build -> build.isBuilding() && build.number.toInteger() < buildNumber && currentStageName(build) != 'C' }
.each{ build -> build.doStop() }
}
So my current stopper is the implementation of currentStageName function.
I'm not able to get the name of the stage.
I've already found some code but it does not work well for me:
#NonCPS
def currentStageName(currentBuild) {
FlowGraphWalker walker = new FlowGraphWalker(currentBuild.getExecution())
for (FlowNode flowNode: walker) {
if(flowNode.isActive()) {
return flowNode.getDisplayName();
}
}
}
FlowNode object does not contain stage name it contains more narrow flow step inside the build.
So the question is:
How to get the current stage of previous build for particular Jenkins job?
Given a FlowNode, you can check if it is the start of a stage by checking if node instanceof StepEndNode. If it is, you can use its LabelAction class to get the name of the stage:
static String getLabel(FlowNode node) {
LabelAction labelAction = node.getAction(LabelAction.class);
if (labelAction != null) {
return labelAction.getDisplayName();
}
return null;
}
I don't think it's useful for your case, but you can also get it from the node that marks the end of a stage (a StepEndNode) by looking up the corresponding start node:
FlowNode startNode = ((StepEndNode) node).getStartNode();
I have set up some folders (Using Cloudbees Folder Plugin).
It sounds like the simplest possible command to be able to tell Jenkins: Build every job in Folder X.
I do not want to have to manually create a comma-separated list of every job in the folder. I do not want to add to this list whenever I want to add a job to this folder. I simply want it to find all the jobs in the folder at run time, and try to build them.
I'm not finding a plugin that lets me do that.
I've tried using the Build Pipeline Plugin, the Bulk Builder Plugin, the MultiJob plugin, and a few others. None seem to support the use case I'm after. I simply want any Job in the folder to be built. In other words, adding a job to this build is as simple as creating a job in this folder.
How can I achieve this?
I've been using Jenkins for some years and I've not found a way of doing what you're after.
The best I've managed is:
I have a "run every job" job (which contains a comma-separated list of all the jobs you want).
Then I have a separate job that runs periodically and updates the "run every job" job as new projects come and go.
One way to do this is to create a Pipeline job that runs Groovy script to enumerate all jobs in the current folder and then launch them.
The version below requires the sandbox to be disabled (so it can access Jenkins.instance).
def names = jobNames()
for (i = 0; i < names.size(); i++) {
build job: names[i], wait: false
}
#NonCPS
def jobNames() {
def project = Jenkins.instance.getItemByFullName(currentBuild.fullProjectName)
def childItems = project.parent.items
def targets = []
for (i = 0; i < childItems.size(); i++) {
def childItem = childItems[i]
if (!childItem instanceof AbstractProject) continue;
if (childItem.fullName == project.fullName) continue;
targets.add(childItem.fullName)
}
return targets
}
If you use Pipeline libraries, then the following is much nicer (and does not require you to allow a Groovy sandbox escape:
Add the following to your library:
package myorg;
public String runAllSiblings(jobName) {
def names = siblingProjects(jobName)
for (def i = 0; i < names.size(); i++) {
build job: names[i], wait: false
}
}
#NonCPS
private List siblingProjects(jobName) {
def project = Jenkins.instance.getItemByFullName(jobName)
def childItems = project.parent.items
def targets = []
for (def i = 0; i < childItems.size(); i++) {
def childItem = childItems[i]
if (!childItem instanceof AbstractProject) continue;
if (childItem.fullName == jobName) continue;
targets.add(childItem.fullName)
}
return targets
}
And then create a pipeline with the following code:
(new myorg.JobUtil()).runAllSiblings(currentBuild.fullProjectName)
Yes, there are ways to simplify this further, but it should give you some ideas.
I developed a Groovy script that does this. It works very nicely. There are two Jobs, initBuildAll, which runs the groovy script and then launches the 'buildAllJobs' jobs. In my setup, I launch the InitBuildAll script daily. You could trigger it another way that works for you. We aren't full up CI, so daily is good enough for us.
One caveat: these jobs are all independent of one another. If that's not your situation, this may need some tweaking.
These jobs are in a separate Folder called MultiBuild. The jobs to be built are in a folder called Projects.
import com.cloudbees.hudson.plugins.folder.Folder
import javax.xml.transform.stream.StreamSource
import hudson.model.AbstractItem
import hudson.XmlFile
import jenkins.model.Jenkins
Folder findFolder(String folderName) {
for (folder in Jenkins.instance.items) {
if (folder.name == folderName) {
return folder
}
}
return null
}
AbstractItem findItem(Folder folder, String itemName) {
for (item in folder.items) {
if (item.name == itemName) {
return item
}
}
null
}
AbstractItem findItem(String folderName, String itemName) {
Folder folder = findFolder(folderName)
folder ? findItem(folder, itemName) : null
}
String listProjectItems() {
Folder projectFolder = findFolder('Projects')
StringBuilder b = new StringBuilder()
if (projectFolder) {
for (job in projectFolder.items.sort{it.name.toUpperCase()}) {
b.append(',').append(job.fullName)
}
return b.substring(1) // dump the initial comma
}
return b.toString()
}
File backupConfig(XmlFile config) {
File backup = new File("${config.file.absolutePath}.bak")
FileWriter fw = new FileWriter(backup)
config.writeRawTo(fw)
fw.close()
backup
}
boolean updateMultiBuildXmlConfigFile() {
AbstractItem buildItemsJob = findItem('MultiBuild', 'buildAllProjects')
XmlFile oldConfig = buildItemsJob.getConfigFile()
String latestProjectItems = listProjectItems()
String oldXml = oldConfig.asString()
String newXml = oldXml;
println latestProjectItems
println oldXml
def mat = newXml =~ '\\<projects\\>(.*)\\<\\/projects\\>'
if (mat){
println mat.group(1)
if (mat.group(1) == latestProjectItems) {
println 'no Change'
return false;
} else {
// there's a change
File backup = backupConfig(oldConfig)
def newProjects = "<projects>${latestProjectItems}</projects>"
newXml = mat.replaceFirst(newProjects)
XmlFile newConfig = new XmlFile(oldConfig.file)
FileWriter nw = new FileWriter(newConfig.file)
nw.write(newXml)
nw.close()
println newXml
println 'file updated'
return true
}
}
false
}
void reloadMultiBuildConfig() {
AbstractItem job = findItem('MultiBuild', 'buildAllProjects')
def configXMLFile = job.getConfigFile();
def file = configXMLFile.getFile();
InputStream is = new FileInputStream(file);
job.updateByXml(new StreamSource(is));
job.save();
println "MultiBuild Job updated"
}
if (updateMultiBuildXmlConfigFile()) {
reloadMultiBuildConfig()
}
A slight variant on Wayne Booth's "run every job" approach. After a little head scratching I was able to define a "run every job" in Job DSL format.
The advantage being I can maintain my job configuration in version control. e.g.
job('myfolder/build-all'){
publishers {
downstream('myfolder/job1')
downstream('myfolder/job2')
downstream('myfolder/job2')
}
}
Pipeline Job
When running as a Pipeline job you may use something like:
echo jobNames.join('\n')
jobNames.each {
build job: it, wait: false
}
#NonCPS
def getJobNames() {
def project = Jenkins.instance.getItemByFullName(currentBuild.fullProjectName)
project.parent.items.findAll {
it.fullName != project.fullName && it instanceof hudson.model.Job
}.collect { it.fullName }
}
Script Console
Following code snippet can be used from the script console to schedule all jobs in some folder:
import hudson.model.AbstractProject
Jenkins.instance.getAllItems(AbstractProject.class).each {
if(it.fullName =~ 'path/to/folder') {
(it as AbstractProject).scheduleBuild2(0)
}
}
With some modification you'd be able to create a jenkins shared library method (requires to run outside the sandbox and needs #NonCPS), like:
import hudson.model.AbstractProject
#NonCPS
def triggerItemsInFolder(String folderPath) {
Jenkins.instance.getAllItems(AbstractProject.class).each {
if(it.fullName =~ folderPath) {
(it as AbstractProject).scheduleBuild2(0)
}
}
}
Reference pipeline script to run a parent job that would trigger other jobs as suggested by #WayneBooth
pipeline {
agent any
stages {
stage('Parallel Stage') {
parallel {
stage('Parallel 1') {
steps {
build(job: "jenkins_job_1")
}
}
stage('Parallel 2') {
steps {
build(job: "jenkins_job_2")
}
}
}
}
}
The best way to run an ad-hoc command like that would be using the Script Console (can be found under Manage Jenkins).
The console allows running Groovy Script - the script controls Jenkins functionality. The documentation can be found under Jenkins JavaDoc.
A simple script triggering immediately all Multi-Branch Pipeline projects under the given folder structure (in this example folder/subfolder/projectName):
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject
import hudson.model.Cause.UserIdCause
Jenkins.instance.getAllItems(WorkflowMultiBranchProject.class).findAll {
return it.fullName =~ '^folder/subfolder/'
}.each {
it.scheduleBuild(0, new UserIdCause())
}
The script was tested against Jenkins 2.324.