gitjenkinsjenkins-pipeline

Building a Multibranch Pipeline with a jenkinsfile from another repo


So I'm trying to make a Multibranch Pipeline for a few different projects.

These are the basic requirements:

  1. three jobs dev, stage, prod for each client
  2. for each job, pull the respective branch from each repo and build a bot
  3. If anything changes in a repo that a job is using, trigger a build for that environment

So these requirements are pretty straightforward.

But there's a fourth requirement. What I'm trying to figure out is if I can have a repo that can hold all of my jenkinsfiles and then build all the branches of another repo. Is this possible? All other answers seem to point to deprecated solutions, such as a freestyle Multibranch project.


Solution

  • Is it possible to build a Multibranch Pipeline with a jenkinsfile from another repo?

    Short answer: No, it's not, since each Job in Multibranch Pipeline always references the Jenkinsfile from the same branch (hence, from the same repo) it is configured to monitor. And the branches which do not contain Jenkinsfile are not indexed.

    Extended answer: In order to achieve more or less what you're asking for, I would do the following:

    1. Create a repo with custom Jenkinsfiles (per-branch, per-client, per-env... whatever). Each Jenkinsfile will describe the stages you want to execute in each particular case. Use Scripted Pipeline syntax.
    2. Add another Jenkinfile to your product repo where you: checkout the dedicated repo with your custom pipelines, load a pipeline and execute it.
    3. Configure Multibranch Pipeline for the product repo.

    Example

    git@github.com:your-org/custom-pipelines.git/Jenkinsfile-dev

    // Jenkinsfile-dev
    
    def stages() {
        stage ("Checkout") {
            checkout scm
        }
    
        stage ("Build") {
    
        }
    
        stage ("Test") {
    
        }
    }
    
    return this
    

    git@github.com:your-org/product-repo.git/Jenkinsfile

    // Jenkinsfile
    
    node ("ubuntu") {
        // Checkout custom Jenkinsfiles
        stage ("Checkout pipelines") {
            git url: "git@github.com:your-org/custom-pipelines.git", 
                branch: "master", 
                credentialsId: "github-ssh"
        }
    
        load ("Jenkinsfile-${env.BRANCH_NAME}").stages()
    }