0

I require a setup in jenkins, which enables me to trigger a jenkins job based on a push event to a specific branch in github. tried so many methods neither worked.

2

Install the git plugin, add credentials for the account you want it to use, then set the job to use SCM Polling. It will check on a preset interval for changes to that repo and trigger when changes are detected. If you need instant triggering upon push, you're looking for webhooks, which is significantly more difficult to set up. I find that polling every 2 minutes or so is good enough in most cases. Here's a decent example: https://www.baeldung.com/jenkins-job-schedule

0

If you're using the declarative DSL, you can use when

Suppose the branch you're interested in is main, have a stage like:

.
.
.
stages {
  stage('Specific Branch'}
  when { branch 'main' }
  steps {
    // only executed when the main branch is changed
  }
}
.
.
.

From the Jenkins docs:

Built-in Conditions

branch

Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch 'master' }. Note that this only works on a multibranch Pipeline.

The optional parameter comparator may be added after an attribute to specify how any patterns are evaluated for a match: EQUALS for a simple string comparison, GLOB (the default) for an ANT style path glob (same as for example changeset), or REGEXP for regular expression matching. For example: when { branch pattern: "release-\d+", comparator: "REGEXP"}

While this will only execute changes to the main branch, you still need to configure the job to be executed when changes to that branch are made. This can be done with the job dsl:

This slightly modified example is taken from the DSL plugin repo:

pipelineJob('job-dsl-plugin') {
  definition {
    cpsScm {
      scm {
        git {
          remote {
            url('https://github.com/your/repo')
          }
          branch('*/main')
        }
      }
      lightweight()
    }
  }
}
1
  • as docs says this is applicable only on multi-branch pipeline, is there a way this can be achieved jenkins pipeline job. Nov 5 '20 at 0:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.