Skip to content

Instantly share code, notes, and snippets.

@CSTDev
Last active January 9, 2023 04:32
Show Gist options
  • Save CSTDev/904cb5f0e86abaa77bdc42a6c8afd4be to your computer and use it in GitHub Desktop.
Save CSTDev/904cb5f0e86abaa77bdc42a6c8afd4be to your computer and use it in GitHub Desktop.
Monorepo Jenkinsfile and groovy script that will create a Multi-branch pipeline for each project that has a Jenkinsfile within your repository, put at the top level of your repo and create a job in Jenkins that runs the Jenkinsfile. Useful for when you're using a monorepo and have multiple Jenkinsfiles in multiple sub directories. This can still…
pipeline {
agent {
label 'docker'
}
stages{
stage('Create jobs'){
steps{
container('docker'){
script{
def files = findFiles(glob: ' **/Jenkinsfile')
for (int i = 1; i < files.size(); i++) {
echo files[i].name
def filePath = files[i].path
def pathWithoutFile = filePath.replace('/Jenkinsfile', '')
def jobName = "YourPrefix-" + ( pathWithoutFile =~ /([^\/]+)\/?$/)[0][0]
echo filePath
echo jobName
if(Jenkins.instance.getItemMap()[jobName] == null){
echo "Job ${jobName} does not exist, creating..."
createJob(filePath, jobName)
}else{
echo "Job ${jobName} already exists."
}
}
}
}
}
}
}
}
def createJob(filePath, jobName){
jobDsl targets: '*.groovy',
removedJobAction: 'IGNORE',
removedViewAction: 'IGNORE',
lookupStrategy: 'JENKINS_ROOT',
additionalParameters: [jenkinsfile: filePath, Name: jobName]
}
// A new UUID must be generated for the first run and re-used for your Job DSL, the plugin updates jobs based on ID
UUID uuid = UUID.fromString("5f8becfc-e881-4ca7-9e5e-06de8acfa15c") // generate one @ https://www.uuidgenerator.net
multibranchPipelineJob("${Name}") {
displayName "${Name}"
description "Builds ${Name}"
configure {
it / sources / 'data' / 'jenkins.branch.BranchSource' << {
source(class: 'jenkins.plugins.git.GitSCMSource') {
id(uuid)
remote("<Git repo url>")
credentialsId("<Credentials ID for Git repo>")
includes('*')
excludes('')
ignoreOnPushNotifications('false')
traits {
'jenkins.plugins.git.traits.BranchDiscoveryTrait'()
}
}
}
// customise the branch project factory
it / factory(class: "org.jenkinsci.plugins.workflow.multibranch.WorkflowBranchProjectFactory") << {
owner(class:"org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject", reference: "../..")
scriptPath("${jenkinsfile}")
}
}
}
@poloka
Copy link

poloka commented Jan 6, 2023

@mainameiz not quite. If I follow this example it looks like this creates individual jobs for building within the monorepo. The cloudbees example would look to just build everything if it found a change in say the ‘packages’ folder. Now if that folder had 100’s of npm projects I only want to build the one that had an update. @CSTDev am I following your solution correctly? Do you have some screenshots of your generated jobs associated to the monorepo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment