I have a requirement to upload zip file to appDynamics, i need to use the httpsrequest plugin for that from my jenkins pipeline
upload request for appdynamics:
curl -v -H Content-Type:application/octet-stream --upload-file UISampleApp.app.dSYM.zip --user Example account:Example-License-Key-4e8ec2ae6cfe https://api.eum-appdynamics.com/v2/account/Example+account/ios-dsym
we are using a shell to execute the above request now but I am trying to find out how to sent multiple zip files using httpsRequest plugin
Following Code worked for me :
def response = httpRequest(acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_ZIP',
customHeaders : [[name: "authorization" , value : "${authToken}"],[name: 'x-username' , value: 'admin']],
httpMode: 'POST', ignoreSslErrors: true,
multipartName: '<fileName>', timeout: 900,
responseHandle: 'NONE', uploadFile: "<filePath>",
url: "${url}")
Looks like httprequest plugin does not support uploading zip file. This is my observation.
I think upload will use Content-Type: multipart/form-data. But httpRequest plugin is not supporting this type. However it supports APPLICATION_OCTETSTREAM(ContentType.APPLICATION_OCTET_STREAM)
Could you post output from your curl?
Related
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 have configured a Github web hook with the below settings:
Payload URL: https:///github-webhook/
Content Type: application/x-www-form-urlencoded
Events : Pushes, Pull Requests
The Jenkins job that I have, is a pipeline job that has the below enabled:
Build Trigger: GitHub hook trigger for GITScm polling
With the above configuration, I see that in response to an event ie; push/PR in GitHub, the jenkins job gets triggered successfully. In GitHub, under Recent Deliveries for the web hook, I see the details of the payload and a successful Response of 200.
I am trying to get the payload in Jenkins Pipeline for further processing. I need some details eg: PR URL/PR number, refs type, branch name etc for conditional processing in the Jenkins Pipeline.
I tried accessing the "payload" variable (as mentioned in other stack overflow posts and the documentations available around) and printing it as part of the pipeline, but I have had no luck yet.
So my question is, How can I get the payload from GitHub web hook trigger in my Jenkins Pipeline ?
You need to select Content type: application/json in your webhook in GitHub. Then you would be able to access any variable from the payload GitHub sends as follows: $. pull_request.url for pr url, for example.
Unsure if this is possible.
With the GitHub plugin we use (Pipeline Github), PR number is stored in the variable CHANGE_ID.
PR URL is pretty easy to generate given the PR number. Branch name is stored in the variable BRANCH_NAME. In case of pull requests, the global variable pullRequest is populated with lots of data.
Missing information can be obtained from Github by using their API. Here's an example of checking if PR is "behind", you can modify that to your specific requirements:
def checkPrIsNotBehind(String repo) {
withCredentials([usernamePassword(credentialsId: "<...>",
passwordVariable: 'TOKEN',
usernameVariable: 'USER')]) {
def headers = ' -H "Content-Type: application/json" -H "Authorization: token $TOKEN" '
def url = "https://api.github.com/repos/<...>/<...>/pulls/${env.CHANGE_ID}"
def head_sha = sh (label: "Check PR head SHA",
returnStdout: true,
script: "curl -s ${url} ${headers} | jq -r .head.sha").trim().toUpperCase()
println "PR head sha is ${head_sha}"
headers = ' -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $TOKEN" '
url = "https://api.github.com/repos/<...>/${repo}/compare/${pullRequest.base}...${head_sha}"
def behind_by = sh (label: "Check PR commits behind",
returnStdout: true,
script: "curl -s ${url} ${headers} | jq -r .behind_by").trim().toUpperCase()
if (behind_by != '0') {
currentBuild.result = "ABORTED"
currentBuild.displayName = "#${env.BUILD_NUMBER}-Out of date"
error("The head ref is out of date. Please update your branch.")
}
}
}
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)
Need some help on fetching the GitHub payload into the Jenkins file without installing any plugin.
If anyone can provide the Jenkins file code snippet to access the GitHub payload from the webhook. it would be of great help.
I am able to call the Jenkins job from GitHub webhook. but need the payload as well to process further.
Any help would be appreciated. Thanks.
Please find the below groovy script:
stage('Pull Request Info') {
agent {
docker {
image 'maven'
args '-v $HOME/.m2:/home/jenkins/.m2 -ti -u 496 -e MAVEN_CONFIG=/home/jenkins/.m2 -e MAVEN_OPTS=-Xmx2048m'
}
}
steps {
script {
withCredentials([usernameColonPassword(credentialsId: "${env.STASH_CREDENTIAL_ID}",
variable: 'USERPASS')]) {
def hasChanges = maven.updateDependencies()
if (hasChanges != '') {
def pr1 = sh(
script: "curl -s -u ${"$USERPASS" } -H 'Content-Type: application/json' https://xx.example/rest/some/endpoint",
returnStdout: true
)
def pr = readJSON(text: pr1)
println pr.fromRef
}
}
}
}
}
Above script uses, curl to fetch the details about Pull request. I have stored the credentials in the jenkins and created an environment variable for the credentialId.
You can replace the url with your endpoint. You can also modify the script to use jq if you have jq installed in the machine.
In this case, I'm using readJSON to parse the JSON which is part of pipeline utilities plugin. My question would be, why not use the plugin as it provides the needed functionalities?
If you still dont want to use plugin, take a look at json parsing with groovy.
We use jenkins, sonarqube 5.5, maven and git. When developers create a new git branch and push it, jenkins analyses the branch too, so the developers can fix everything before merging. To avoid this development branch analysis mixing up with the master branch analysis, jenkins passes the branch name into the analysis. The causes sonarqube to create a new project for each branch. So far that's ok.
But recently we switched from one default quality gate for all projects to different quality gates for projects under active development and projects which are just in maintenance.
So how can we tell sonar when creating an new project for a new branch which quality gate to use? Until some versions ago, there was a sonar.qualitygate property which could be set. But now this is deprecated. So what's the new way to define the proper quality gate for a newly created project?
You can use the rest api provided by Sonar.
Step 1. Create gate
def result = ["curl", "--user", auth, "-X", "POST", "-H", "Content-Type: application/json", "-d", "{'name':'" + qualityGateName + "'}", "https://yoursonarserver/api/qualitygates/create"].execute().text
Step 2 Bind project into the gate
["curl", "--user", auth, "-X", "POST", "-H", "Content-Type: application/json", "-d", "{'gateId':'"+qualityGateId+"','projectId':'"+projectId+"'}", "https://yoursonarserver/qualitygates/select"].execute().text
About how to get the projectId and qualityGateId, you can use the following two apis
Get project ID
String result = ["curl", "--user", auth , "-X", "GET", "-H", "Accept: application/json", "https://yoursonarserver/api/projects/index", "-d", "search=" + projectName ].execute().text
Get Quality gate id
def result = ["curl", "--user", auth, "-X", "GET", "-H", "Accept: application/json", "https://yoursonarserver/api/qualitygates/list"].execute().text
The above two apis will get a list of ids, so you need parse them based the project name.
Br,
Tim