I want to setup Jenkins pipeline trigger when PR is merged to master branch. I have setup Webhook in GitHub repo pointing to Jenkins url http://jenkins.example.com:8080/github-webhook/ and selected following events
Pull request review comments
Pull request reviews
Pull requests
in my Jenkinsfile I use this
triggers {
pullRequestReview(reviewStates: ['approved'])
}
But it failed with this error
WorkflowScript: 6: Invalid trigger type "pullRequestReview". Valid trigger types: [upstream, cron, parameterizedCron, GenericTrigger, githubPush, pollSCM] # line 6, column 9.
If I want to trigger the build when PR is merged to master, what I should user in triggers ?
Here is what you need:
GenericTrigger(
genericVariables: [
[key: 'action', value: '$.action'],
[key: ‘merged, value: '$.pull_request.merged]
],
causeString: 'Triggered on pr merge,
token: ‘<your-token>’,
printContributedVariables: true,
printPostContent: true,
silentResponse: false,
regexpFilterText: '$action#$merged,
regexpFilterExpression: ‘closed#true'
)
}
And you don't need to select Pull request review comments and
Pull request reviews events. Just Pull requests is enough for this case.
Related
I have a simple Jenkins pipeline job that does a bunch of things and calls other jobs. There is no repo associated with the job. But this job should be called when a pull request is created in a certain repo in Bitbucket. This was easy with Gitlab where I just had to add a webhook with the Jenkins job url on Gitlab. How do I achieve this with Bitbucket? It looks like it always needs a repo url in Jenkins for the webhook to be triggered but I have no repo.
Ex my pipeline job on Jenkins is
stage('Stage 1'){
echo "hello, world!"
}
}
I want to trigger this build when a PR is created on Bitbucket for repo xyz.
Or in general how to make Jenkins pipeline jobs with pipeline script and Bitbucket Webhooks work? All either speak about freestyle job or multibranch job or pipeline job with Jenkinsfile
For this, you can use the Generic Webhook Trigger Plugin. The Job will be identified by the token you add to the Job. Here is a sample Jenkins Pipeline and how you can extract information from the Webhook request to determine it's coming from a PR.
pipeline {
agent any
triggers {
GenericTrigger(
genericVariables: [
[key: 'PR_ID', value: '$.pullrequest.id', defaultValue: 'null'],
[key: 'PR_TYPE', value: '$.pullrequest.type', defaultValue: 'null'],
[key: 'PR_TITLE', value: '$.pullrequest.title', defaultValue: 'null'],
[key: 'PR_STATE', value: '$.pullrequest.state', defaultValue: 'null'],
[key: 'PUSH_DETAILS', value: '$.push', defaultValue: 'Null']
],
causeString: 'Triggered By Bitbucket',
token: '12345678',
tokenCredentialId: '',
printContributedVariables: true,
printPostContent: true,
silentResponse: false
)
}
stages {
stage('ProcessWebHook') {
steps {
script {
echo "Received a Webhook Request from Bitbucket."
if(PR_ID != "null") {
echo "Received a PR with following Details"
echo "PR_ID: $PR_ID ; PR_TYPE: $PR_TYPE ; PR_TITLE: $PR_TITLE ; PR_STATE: $PR_STATE"
// If the PR state is either MERGED or DECLINED we have to do some cleanup
if(PR_STATE == "DECLINED" || PR_STATE == "MERGED") {
// Do your cleanup here, You should have all the PR Details to figure out what to clean
echo "Cleaning UP!!!!!!"
}
} else if(PUSH_DETAILS != "null") {
echo "This is a commit."
}
}
}
}
}
}
Then in Bitbucket, you will have the webhook URL like below.
JENKINS_URL/generic-webhook-trigger/invoke?token=12345678
You can read more about the webhook messages Bitbucket will send from here.
I'm using Jenkins 2.346.2
The repository is located on bitbucket.org (cloud, not local server).
I want the build status to be sent to bitbucket and to be displayed as the PR build status.
I'm trying the plugin: https://plugins.jenkins.io/bitbucket-build-status-notifier/
The configuration is (multibranch pipeline project):
def notifyBitbucket(String state) {
notifyBitbucket(
commitSha1: 'a0e5012be0e8e89d122cc773a964c0en3a1a656b2',
credentialsId: 'jenkins_bitbucket_ssh',
disableInprogressNotification: false,
considerUnstableAsSuccess: true,
ignoreUnverifiedSSLPeer: true,
buildStatus: state,
buildName: 'Performance Testing',
buildUrl: 'https://bitbucket.org',
includeBuildNumberInKey: false,
prependParentProjectKey: false,
projectKey: '',
stashServerBaseUrl: 'https://bitbucket.org')
}
But what I get is a returned bitbucket page saying 'Resource not found'.
Currently, the only credentials I can use to connect to bitbucket is SSH key pair.
And they work okay for pulling the code. I'm trying to use this key for the notification plugin as well. Is this wrong?
Could anyone let me know how to specify the path to the project in this case, please?
One option you can consider is using the Bitbucket API, which would remove the need for an external plugin. The endpoint you need to call is:
${BITBUCKET_API_HEAD}/commit/${env.COMMIT_HASH}/statuses/build
More on this in the documentation. Here is how I have done it:
httpRequest([
acceptType : 'APPLICATION_JSON',
authentication : '<credentials>',
contentType : 'APPLICATION_JSON',
httpMode : 'POST',
requestBody : '''{
"key":"<unique-key>",
"name":"PR-Branch-Build",
"url":"<path-to-jenkins-build>/''' + env.BUILD_NUMBER + '''/pipeline",
"description":"Build status: '''+ BUILD_STATUS +'''",
"state":"'''+ BUILD_STATUS +'''"
}''',
responseHandle : 'NONE',
url : "${BITBUCKET_API_HEAD}/commit/${env.COMMIT_HASH}/statuses/build",
validResponseCodes: '200,201'
])
I want to create a process in Jenkins when one job is building it should internally call another job that is generating a SONAR report for the same code pull request.
When I am trying to call API to trigger Jenkins job automatically.
https://jenkins.com/job/DPNew/job/xyz/buildWithParameters?token=DW&FROM_HASH=195c8df91791768f3098ce260eb2dd8728&REPO_NAME=_python&PROJECT_KEY=%7Eabc&EMAIL=abc#gmail.com&FROM_BRANCH_NAME=feature%2FDO-451&TO_BRANCH_NAME=Port-2.7&PR_ID=622"
I am getting below error in response.
content: "<html><head><body style='background-color:white;
color:white;'>\n\n\nAuthentication required\n<!--\nYou are authenticated as: anonymous\nGroups that you are in:\n \nPermission you need to have (but didn't):
hudson.model.Hudson.Read\n ... which is implied by: hudson.security.Permission.GenericRead\n ... which is implied by:
hudson.model.Hudson.Administer\n-->\n\n</body></html>
I have already created Jenkins API token in 'user -> configure'
Edit 1:
The first Jenkin job is triggered by a pull request from Bitbucket, and the UI in bitbucket shows if the build is successful and if the build is a success it shows a sonar report.
What should I do to resolve this issue?
Instead of API call, use job, this will also make it so you can use paramers from your sonar report job and display them here/use them.
example:
pipeline {
agent any
stages {
stage('stage_name') {
steps {
build job: 'JOB_NAME'
}
}
}
}
Or with parameters:
pipeline {
agent any
stages {
stage('stage_name') {
steps {
build job: 'JOB_NAME_HERE', propagate: true, parameters:
[
[
$class: 'StringParameterValue',
name: 'STRING_NAME_HERE',
value: "STRING_VALUE_HERE"
]
]
}
}
}
}
propagate: true means that the original job will fail if JOB_NAME_HERE fails.
triggers { pollSCM('H */4 * * 1-5') } will this work for merge to branch
I see we have 3 options for triggers this seems to be fo declarative
corn
pollScm
upstream
where in for scripted pipeline is that something like this
properties([pipelineTrigger([triggers('gitPush')])])
OR
properties([pipelineTriggers([githubPush()])])// With this should I also enable a option on Jenkins instance
You can also use Generic Webhook Trigger plugin.
You will need to create a webhook in github and in Jenkins Pipeline something like below.
triggers {
GenericTrigger( genericVariables: [
[defaultValue: '', key: 'commit_author', regexpFilter: '', value: '$.pusher.name'],
[defaultValue: '', key: 'ref', regexpFilter: '', value: '$.ref']
],
causeString: '$commit_author committed to $ref',
printContributedVariables: false,
printPostContent: false,
regexpFilterText: '$ref',
regexpFilterExpression: 'refs/heads/develop',
token: '12345'
}
Hope this helps.
Use something like this in you Jenkinsfile. Use Only those option which you need. Remove which you don't want.
pipeline {
agent any
triggers {
github(
triggerOnPush: true,
triggerOnMergeRequest: true,
triggerOpenMergeRequestOnPush: "source",
branchFilterType: "All",
triggerOnNoteRequest: false)
}
stages {
...
}
}
NOTE: Make sure you have done all the webhook configuration bewteen github and jenkins. and installed webhook plaugin on jenkins
I have the following Jenkins setup:
A multi-branch pipeline which sometimes (on certain tag builds) triggers
a pipeline that builds an installer from the upstream artifacts.
In the upstream MB-pipeline, I have the following fragments:
options {
copyArtifactPermission('my-downstream-project');
}
post {
success {
script {
if (isRelease()) {
build job: 'my-downstream-project'
}
}
}
}
The downstream pipeline, I then try to grab the artifacts:
copyArtifacts projectName: 'my-upstream-project',
selector: upstream(),
filter: '*.jar',
fingerprintArtifacts: true
While the downstream build is started, it fails with:
ERROR: Unable to find project for artifact copy: hds-access-code-cache
This may be due to incorrect project name or permission settings; see help for project name in job configuration.
My understanding so far:
While I can't configure the Copy Artifact permission via the configuration UI for the MB-pipeline, the option is accepted and should work.
The examples I can find would use projectName: 'my-upstream-project/tag-name' as that's the actual job. I don't have a fixed branch or tag, though.
How can I correctly access the upstream artifact?
It is possible to pass down the job name as parameter.
Change the upstream pipeline to:
build job: 'my-downstream-project',
parameters: [string(name: 'upstreamJobName', value: env.BRANCH_NAME)]
Add the parameter to the downstream pipeline:
parameters {
string(name: 'upstreamJobName',
defaultValue: '',
description: 'The name of the job the triggering upstream build'
)
}
And change the copy directive to:
copyArtifacts projectName: "my-upstream-project/${params.upstreamJobName}",
selector: upstream(),
filter: '*.jar',
fingerprintArtifacts: true
Et voila:
Copied 1 artifact from "My Upstream Project » my-tag" build number 1