Search code examples
gitjenkinsjenkins-pipelinepipelinejenkins-groovy

Prevent Jenkins job from launching additional jobs with git commit


I'm attempting to create a Jenkins pipeline which does the following steps at a high level:

  1. Send build notifications
  2. Run lint tests
  3. Run CI tests
  4. Update version information in a couple of files
  5. Use git to commit the updates to the files, create tags, and push changes to origin
  6. Upload files in project to another system
  7. Send notifications

I want this pipeline to execute when a commit happens to specific branches. I have this working now, but the issue is when the job commits the new changes during the build (in step 5 above), it launches a new build and essentially enters an infinite loop.

I know this is working by design right now, but is there anyway way to prevent a new build job from executing? Can I do something within the Jenkins pipeline to prevent the new commit from launching a new Jenkins job, or would this require a whole rework of the workflow?


Solution

  • You can use generic-webhook-plugin,

    For instance, GitHub webhooks in Jenkins are used to trigger the build whenever a developer commits something to the branch, in each webhook we have following info

    git repository name
    branch which was changed
    commit id
    commit message
    commit author
    etc ...
    

    To avoid loop

    • save Jenkins commit ID to file and add the file to git ignore
    • read remote commit ID from push using generic webhook trigger
    • compare local file commit ID with Remote commit ID
    • If same it's mean commit from Jenkins, if not it's mean commit is not from Jenkins

    Here is the snippet that may help or change accordingly, it will not create look

    #!/bin/bash
    webhook_commit_id=$commit
    commit_by_jenkins=commit_by_jenkins.txt
    if [ ! -f $commit_by_jenkins ]
    then
        echo "creating local file name commit_by_jenkins.txt, please add this file to git ignore"
        touch commit_by_jenkins.txt
    fi
    jenkins_commit=`cat commit_by_jenkins.txt`
    if [ "${webhook_commit_id}" == "${jenkins_commit}" ]; then 
        echo "commit by jekins server, ignoring commit"
    else
          echo "commiting code from jenkins servver"
          git add -A && git commit -m "commit by jenkins server" && git rev-parse HEAD > commit_by_jenkins.txt
    fi