Jenkins build: notify Bitbucket cloud - jenkins

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'
])

Related

Problem with sending Get request from jenkins pipeline job from Jenkins slave

I am using HTTP-request in Jenkins pipeline job to send Get request from Jenkins slave, the response code is 200, response content is null, but if I send the request from Jenkins master, I can get response content correctly, how can I solve this problem? below is the command I used HTTP-request in Jenkins pipeline
httpRequest acceptType: 'APPLICATION_JSON',
authentication: env.MY_CREDENTIAL,
contentType: 'APPLICATION_JSON',
url: env.MyURI,
wrapAsMultipart: false
I see nothing wrong with your request but as you commented, looks like the response is string?
You can add consoleLogResponseBody to see how the response looks like.
def response = httpRequest(
authentication: env.MY_CREDENTIAL,
consoleLogResponseBody: true,
url: env.MyURI,
wrapAsMultipart: false
)
And you should be able to parse it simply like this
def json = readJSON(text: response.content)

Jenkins pipeline trigger on merge to master

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.

How to trigger a build on commit to branch in scripted pipeline

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

Artifactory build options for maven build and issues

I am new to Artifactory and I find that there is a lot of documentation on the different ways to get artifacts to Artifactory but nothing that is complete.
For example:
The pipeline plugin used by jenkins:
sample code:
node {
def server = Artifactory.newServer url: SERVER_URL, credentialsId: CREDENTIALS
def rtMaven = Artifactory.newMavenBuild()
stage 'Build'
git url: 'https://github.com/jfrogdev/project-examples.git'
stage 'Artifactory configuration'
rtMaven.tool = MAVEN_TOOL // Tool name from Jenkins configuration
rtMaven.deployer releaseRepo:'libs-release-local', snapshotRepo:'libs-snapshot-local', server: server
rtMaven.resolver releaseRepo:'libs-release', snapshotRepo:'libs-snapshot', server: server
def buildInfo = Artifactory.newBuildInfo()
stage 'Exec Maven'
rtMaven.run pom: 'maven-example/pom.xml', goals: 'clean install', buildInfo: buildInfo
stage 'Publish build info'
server.publishBuildInfo buildInfo
}
I am not sure how to set up some variables like CREDENTIALS. specially if I want to use api key not user id and password.
Also, if I want to use the Artifactory rest API to build and promote my project(Maven Build). should I be using:
curl -X PUT "http://localhost:8080/artifactory/api/build" -H "Content-Type: application/json" --upload-file build.json
Where build.json is the sample JSON at https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API under Build Upload.
If i use the API do i still need the above jenkins plugin code or can just use the API?
Where do I pass my credentials (Userid and APi key) in the curl command?
If any experienced user could guide me with these questions that will be of great help.

Updating Jira tickets from Jenkins workflow (jenkinsfile)

How can I update a jira issue from within a Jenkinsfile (jenkins-worflow/pipeline)?
Is there a way I could use the Jira Issue Updater plugin as a step in the Jenkinsfile?
I know I could use the Jira RestAPI, but I'm trying to figure out if I can re-use the functionality provided by the jira-updater-issue.
What I'm looking for is a something similar to the example below calling Junit archiver, and atifact archiver, but calling jira updater.
node {
git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
def mvnHome = tool 'M3'
sh "${mvnHome}/bin/mvn -B -Dmaven.test.failure.ignore verify"
step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
}
The Jira Plugin is compatible with Pipeline.
This should work:
step([$class: 'hudson.plugins.jira.JiraIssueUpdater',
issueSelector: [$class: 'hudson.plugins.jira.selector.DefaultIssueSelector'],
scm: [$class: 'GitSCM', branches: [[name: '*/master']],
userRemoteConfigs: [[url: 'https://github.com/jglick/simple-maven-project-with-tests.git']]]])
You can get a full reference in the built-in Pipeline Snippet Generator.
The JIRA Steps Plugin provides a more declarative way to update an existing Jira Ticket:
node {
stage('JIRA') {
# Look at IssueInput class for more information.
def testIssue = [fields: [ // id or key must present for project.
project: [id: '10000'],
summary: 'New JIRA Created from Jenkins.',
description: 'New JIRA Created from Jenkins.',
customfield_1000: 'customValue',
// id or name must present for issuetype.
issuetype: [id: '3']]]
response = jiraEditIssue idOrKey: 'TEST-01', issue: testIssue
echo response.successful.toString()
echo response.data.toString()
}
}
Since you would like to use the Jenkinsfile to define your pipeline, that should be the preferred way for you to go...
As this was way harder for me than it should be, here is a working example. This will update a custom field of a ticket with a specific value:
step([$class: 'IssueFieldUpdateStep',
issueSelector: [$class: 'hudson.plugins.jira.selector.ExplicitIssueSelector', issueKeys: ticket],
fieldId: field,
fieldValue: value
])
The snippet generator did not work for me. The variables ticket, field and value are all strings. Starting from this you can look for options here: https://www.jenkins.io/doc/pipeline/steps/jira/
Yes, seems like this page answers your question:
https://wiki.jenkins-ci.org/display/JENKINS/Jira+Issue+Updater+Plugin
After you install the plugin, add a build step, or pre/post build step to call this plugin
There you can give it the REST URL to your Jira server, the creds and the JQL to find the issues

Resources