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
Related
I am trying to retrigger a downstream job if the job fails during the first build with the error "invalid JWT token", I want this job to retrigger again with changed parameters.
I am able to retrigger it with different parameters as of now, but what I want to achieve here is want the job to retrigger only if I get the error as " invalid Jwt token" only.
can someone help me with this, I am trying to make use of try-catch block
this is the pipeline job as of now
I assume you decide on the error by looking at the log of the second Job. If that's the case have a look at the following. Here I'm using propagate: false
pipeline {
agent any
stages {
stage('Job') {
steps {
script {
def jobBuild = build(job: 'SecondJob', wait: true, propagate: false)
def result = jobBuild.getResult()
if(result == "FAILURE"){
def log = jobBuild.getRawBuild().getLog()
if(log.contains("invalid JWT token")){
echo "Rerunning the JOB!!!!"
} else {
error "Downstream Job failed due to other error."
}
}
}
}
}
}
}
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
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
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')
}
}
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