Triggering a multibranch pipeline job from github enterprise webhook - jenkins

I am attempting to trigger multi-branch pipeline jobs from a GitHub enterprise server. I have the webhook configured to send a notification on all events. The event log on github enterprise shows that the requests to Jenkins are successful, however on the multibranch pipeline the event log is empty.
My multibranch pipeline jobs are being created using JobDSL like so:
multibranchPipelineJob("build_${repo}") {
branchSources {
branchSource {
source {
git {
id("${org}.${repo}")
remote("git#${githubEntrerpise}:${org}/${repo}")
}
}
}
}
configure {
def traits = it / sources / data / 'jenkins.branch.BranchSource' / source / traits
traits << 'jenkins.plugins.git.traits.BranchDiscoveryTrait' {}
}
triggers {
periodic(1) // Trigger every min.
}
orphanedItemStrategy { discardOldItems { numToKeep(10) } }
}
Is there anything I am missing here?

I resolved it by changing the webhook endpoint I was using.
Changing it to the following format solved the issue http://[JENINS_HOST]/git/notifyCommit?url=git#[GIT_REPO].git

Related

How to set the discovery modes for multibranch job created by Job DSL

I'm new to Jenkins and I'm trying to figure something out.
Is there a way to add Branch Sources behavior via Groovy. This is to analyse GitHub projects in SonarQube using Jenkins.
I'm creating a multi-branch pipeline but can't seem to figure out how to add the following behaviours.
These behaviours come by default when the job is created in the UI, but don't appear when the job is created via Groovy.
I've defined this as my pipeline. Any idea how these other parameters can be added in?
multibranchPipelineJob('Foo') {
displayName('Foo')
description('Jenkins')
branchSources {
branchSource {
source {
github {
id('15')
repoOwner('12345')
repository('foo')
repositoryUrl('https://example.com')
configuredByUrl(true)
credentialsId('foo')
traits {
gitBranchDiscovery()
}
}
}
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(10)
}
}
}
I've tried adding in the following parameters but it throws an error.
import jenkins.plugins.git.traits.*
def traits = []
traits.add(new TagDiscoveryTrait())
traits.add(new LocalBranchTrait())
gitSCMSource.setTraits(traits)
Is there a way to create the job via Groovy but with the default settings that would appear when the job is created in the UI?
You can check all available options on your Jenkins by using this URL:
https://<your-jenkins>/plugin/job-dsl/api-viewer/index.html
Branch Discovery Mode
multibranchPipelineJob('Foo') {
branchSources {
branchSource {
source {
github {
traits {
gitHubBranchDiscovery {
strategyId(1)
// strategyId(2)
// strategyId(3)
}
}
}
}
}
}
}
Strategy id:
1 - discover all branches, except branches that are pull request sources
2 - discover only branches that are pull request sources
3 - discover all branches
Pull Request Discovery Mode
multibranchPipelineJob('Foo') {
branchSources {
branchSource {
source {
github {
traits {
gitHubPullRequestDiscovery {
strategyId(1)
// strategyId(2)
// strategyId(3)
}
}
}
}
}
}
}
Strategy id:
1 - discover each pull request once with the discovered revision corresponding to the result of merging with the current revision of the target branch
2 - discover each pull request once with the discovered revision corresponding to the pull request head revision without merging
3 - discover the current pull request revision and the pull request merged with the current target branch revision
Fork Pull Request Discovery Mode
Due to a bug in Jenkins (JENKINS-60874), you have to use the configure block:
multibranchPipelineJob('Foo') {
configure {
def traits = it / 'sources' / 'data' / 'jenkins.branch.BranchSource' / 'source' / 'traits'
traits << 'org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait' {
strategyId(1)
// strategyId(2)
// strategyId(3)
trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustPermission')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustNobody')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustContributors')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustEveryone')
}
}
}
Strategy id:
1 - discover each pull request once with the discovered revision corresponding to the result of merging with the current revision of the target branch
2 - discover each pull request once with the discovered revision corresponding to the pull request head revision without merging
3 - discover the current pull request revision and the pull request merged with the current target branch revision
Trust class:
TrustPermission - trust those with write permission to the repository
TrustNobody - trust nobody
TrustContributors - trust contributors to the repository
TrustEveryone - trust everyone

GitHub Webhook not triggering the Jenkins Pipeline

I want to trigger a pipeline when Pull Request is Merged..ie "action": "closed","merged":"true"
Webhook got 200 response for Jenkins
pipeline.groovy:
pipelineJob(job_name) {
parameters {
stringParam('APP_URL', app_url, 'URL of the Application')
stringParam('APP_MERGE_STATUS', app_merge_status, 'Merge Status to Trigger Job')
booleanParam('MERGED', true, 'Flag to Trigger the job')
stringParam('APP_ARTIFACT_BUCKET', artifact_bucket, 'Bucket url to upload artifacts')
stringParam('payload')
}
triggers {
genericTrigger {
genericVariables {
genericVariable {
key("APP_MERGE_STATUS")
value("\$.action")
expressionType("JSONPath")
}
genericVariable {
key("MERGED")
value("\$pull_request.merged")
expressionType("JSONPath")
}
}
printPostContent(true)
regexpFilterText("\$action")
regexpFilterExpression("")
}
}
Generic Variables I have mentioned are also used to trigger the job without github..[using parameters]
I am not sure how to write the generic trigger variables and regex for the trigger
Scenario: PR is closed and merged
If your Jenkins is exposed to the internet, you can subscribe to the webhook in Github itself
or use jenkins declarative pipeline to make use of
Got the solution..I missed to add "generic-webhook-trigger" in payload url

Gitlab Webhooks (2 Webhooks on the same repo)

So heres the thing ,
We have two webhooks setup on the same repository in Gitlab ,
Webhooks number 1 is set to url : http://jenkins.local/project/job1 (build job from master branch )
Webhooks number 2 is set to url : http://jenkins.local/project/job2 (builds job from branch "1" )
The issue we're trying to overcome is , whenever there is a mergre request being opened
Both of those web hooks are being triggered .
Is there a way to "configure" the webhooks to fire only when a merge reuqest is being made into the master / 1 branch ,
i haven't found such settings in settings -> integrations
Webhook settings info
Currently, the option to restrict webhooks per branch is only available for Push events; for Merge requests events; there isn't a way to restrict/filter.
You have to filter it in your Jenkins job (which job to get fired; if that's also you looking for) as an example of GitLab plugin like this -
Job1:-
triggers {
gitlabPush {
buildOnMergeRequestEvents(true)
targetBranchRegex('master')
}
}
Job2:-
triggers {
gitlabPush {
buildOnMergeRequestEvents(true)
targetBranchRegex('branch1')
}
}

Trigger Input Step in Jenkins via HipChat

I can find tons of information in the internet about integrating HipChat in a scripted Jenkins pipeline. So that works fine for me. But how can I post a status message to HipChat that contains an element to trigger an action back in Jenkins?
Currently I have input steps in Jenkins to approve a deployment to the next stage, e.g. PROD.
I also send a HipChat message if approval is needed which contains a link to JENKINS. That looks like this:
hipchatSend color: "${color}", notify: true, room: "Jenkins Team FooBar", message: "${env.JOB_NAME}#${env.BUILD_NUMBER}: ${message}", textFormat: true
/************** PROD **************/
stage ('Approval for PROD') {
try {
timeout(time: approvalTime, unit: approvalTimeUnit) {
input 'Do you approve the deployment to PROD?'
}
} catch (Exception ex) {
finishBuild = true
}
}
// Stop build if flag was set
if (finishBuild)
return
How can I define actions in that hipChat message? Is there a way that I can approve the next build step within HipChat?
I have not found a tutorial or documentation on how to define other kinds of hipchat messages with this plugin.
I could send a POST request to JENKINS if the message would contain standard HTML. Any ideas on how to do that?
How would it work with cards?
Thanks in advance.

Jenkins Job DSL getting triggered by "Started by SCM change"

I am writing a DSL job to trigger a build only when a pull request is opened or closed (using webhooks). However, in Jenkins, I can see three builds being triggered when I open a pull request - 1 for pull requeste and 2 for started by SCM change.
How can I prevent the builds "Started by SCM change"?
job("dummyjob"){
description('Apply pull request patch, build image and store in archive.')
scm {
git {
remote {
github("user/${project.name}")
refspec('+refs/pull/*:refs/remotes/origin/pr/*')
}
}
}
triggers {
onPullRequest {
setPreStatus()
cancelQueued()
mode {
cron('') //null means no cron (else default 5 minutes), dependent only on hooks
heavyHooks()
}
events {
opened()
closed()
}
}
}
steps {
updateStatusOnGH {
message('Building...')
}
}
}
This is using Github Integration plugin
triggers {
cron(String cronString)
}
Have a look here:
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.jobs.BuildFlowJob.triggers

Resources