Search code examples
jenkinsjenkins-pipeline

Multiple jenkinsfile in one repository


We have a project in a Github repository with multiple Jenkinsfiles:

my-project
  app
    Jenkinsfile
  lib1
    Jenkinsfile
  lib2
    Jenkinsfile

We have created 3 Jenkins pipelines each referring to a Jenkinsfile. enter image description here

Question: How to avoid triggering "app" and "lib1" pipelines when there is a new commit in "lib2"? We don't want to run N jobs every time a commit happens.

I've seen that the issue is addressed in https://issues.jenkins-ci.org/browse/JENKINS-43749, but I haven't found a solution there.


Solution

  • RECENT UPDATE:

    I later fixed this issue using following code snippet: If you see the command dir('servicelayer'), using this to move into the directory, executing git command to find the difference between the commits and raising a flag. This way i have managed 3 Jenkins files in a single repository.

    stage('Validation') {
    steps {
            //Moving in to the directory to execute the commands
            dir('servicelayer') {
                script {
                    //Using the git command to check the difference between previous successful commit. ${GIT_PREVIOUS_SUCCESSFUL_COMMIT} is an environment variable comes with GIT Jenkins plugin
                    //There is a drawback though, if it is the first time you are running this job, this variable is not available and fails the build
                    //For the first time i had to use ${env.GIT_COMMIT} itself at both places to pass the build. A hack but worth it for future builds.
    
                    def strCount = sh(returnStdout: true, script: "git diff --name-only ${env.GIT_COMMIT} ${env.GIT_PREVIOUS_SUCCESSFUL_COMMIT} | grep servicelayer | wc -l").trim()
                    if(strCount=="0") {
                        echo "Skipping build no files updated"
                        CONTINUE_BUILD = false
                    } else {
                        echo "Changes found in the servicelayer module"
                    }
                }
            }
        }
    }
    

    OLD ANSWER:

    You can do it in 2 ways:

    a) Configure your build jobs by adding "Additional Behaviour" -> "Polling ignore commits in certain region" This behaviour will let you add "Whitelisted regions" or "Blacklist the regions" which you do not want to poll for triggering the build job.

    b) Write a custom shell script to verify the files changed per commit and verify the location. This shell script can then be added to your Jenkinsfile and be it Declarative or Scripted you can tweak the behaviour accordingly.

    I will recommend option a) as it is simpler to configure and maintain as well. Hope this helps.

    Additional Behaviour