I'm trying to analyse my source code with Sonar using Jenkins pipelines. To ask Sonar to notify Github with the results I need to specify the Pull Request ID.
How can I get this Pull Request ID from Jenkins Pipelines?
We are using GitHub Organization Folder Plugin to build pull requests, not GitHub pull request builder plugin. That's why $ghprbPullId is not working for me. Any ideas how to get the pull request id in a different way?
Jenkins exposes a global variable named CHANGE_ID:
For a multibranch project corresponding to some kind of
change request, this will be set to the change ID, such as a pull
request number.
This variable is only populated for pull request builds, so you have to disable branch builds and enable PR builds in your pipeline's configuration for branch sources:
My pipeline step then looks like this:
def PULL_REQUEST = env.CHANGE_ID
stage('Analysis') {
withCredentials([[$class: 'StringBinding', credentialsId: '***', variable: 'GITHUB_ACCESS_TOKEN']]) {
withSonarQubeEnv('Sonar') {
withMaven(maven: 'M3') {
sh "mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar " +
"-Dsonar.analysis.mode=preview " +
"-Dsonar.github.pullRequest=${PULL_REQUEST} " +
"-Dsonar.github.oauth=${GITHUB_ACCESS_TOKEN}"
}
}
}
}
You get the PR number through for example env.BRANCH_NAME.
if (env.BRANCH_NAME.startsWith('PR-')) {
def prNum = env.BRANCH_NAME.replace(/^PR-/, '')
...
}
In the case that Thomas' answer doesn't work or apply to you, you may also (possibly) use the branch name to get the Pull Request number by querying the Github REST API. All you need is an API token and the branch name, lookup the pull requests in order of date updated DESC, and find the first PR that matches your branch name. That will have the Pull Request number.
This only works if you have a unique branch name for each pull request (such as a JIRA issue ticket number).
Related
I need a solution to display the results of sonar in the azure pull request.
I tried to do it with a status check by selecting the sonar pipeline in branch policy. It is showing success/fail and redirecting to sonar portal on click.
Is it really possible to show the actual results(vulnarabilities,duplications,etc.,) in the pull requets itself?
please help.
Thanks
After got the result of Sonarqube, you could use DevOps REST API to update the result to Azure pull request.
The flow is : a new pull request created > trigger a pipeline > run REST API to update the pull request description or title.
Add a Powershell task in the pipeline with follow script to update the pull request description and title. You could also refer to the document above to update other properties of the pull request. Please pay attention to PAT, the result of Sonarqube, organization name, project name, repository ID. Here we could use $(System.PullRequest.PullRequestId) to get the pull request ID, thus, the build will fail if it was not triggered by pull request.
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
$connectionToken="<PAT>"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $base64AuthInfo")
$headers.Add("Content-Type", "application/json")
$body = '{"description": "<the result of Sonarqube>","title": "<the result of Sonarqube>"}'
$response = Invoke-RestMethod 'https://dev.azure.com/<organization name>/<project name>/_apis/git/repositories/<repository ID>/pullrequests/$(System.PullRequest.PullRequestId)?api-version=5.0' -Method 'PATCH' -Headers $headers -Body $body
$response | ConvertTo-Json
After configure the pipeline, please enable Build Validation for the branch in project setting >> repositories >> your repo >> policies >> branch >> Build Validation. Then, every time a new pull request created for that branch will trigger the pipeline. You could also find the repository ID in the URL.
Azure dev-ops pipelines have predefined varialbles related to github pull requests. I can use SYSTEM_PULLREQUEST_PULLREQUESTNUMBER for getting PR number that triggered my pipeline. However I get no value from SYSTEM_PULLREQUEST_PULLREQUESTNUMBER when my pipeline is triggered again as a result of merging this PR in the main repo.
My use case is to identify the list of files that were changed in the original PR.
I looked into Azure user predefined variable document but could not see if there is any variable available to get this information.
When the pipeline is ran the second time when it is merged, it is considered to have the trigger type CI not Pull Request. Therefore the PR number is unavailable in this context because there was no PR.
You could also try to save the pull request number to a variable group in the previous run triggered by a pull request.
https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/cli/pipeline-variable-group-secret-nonsecret-variables?view=azure-devops
You could try and steal the pull request number from the commit message. If your PR merge type is set to 'squash commit' you can write some regex to pull the PR number out of the commit message.
https://learn.microsoft.com/en-us/azure/devops/repos/git/merging-with-squash?view=azure-devops#squash-merge
I have a problem, how to close a pull request using Jenkins jobs.
my goal is, I can get a branch, using this branch name to find, if under this branch, a pull request existed.
if yes, then I close this pull request through Github API.
Question, How to get pull request ID through Branch name?
2: if I get pull request ID, how to close this pull request.
Any Solutions?
I finde
I have a pull request trigger for Github in VSTS. I also want to add this trigger to the required checks in Github and show build status on pull request page like below.
I also checked branch protection page on Github but there are no status checks available.
Is it possible to do this in VSTS or do I need to create a PR status server mentioned here ?
I checked Advanced settings => Report build status option and VSTS automatically sends commit status to Github.
Configuration for enabling the GitHub commit status checks in Azure DevOps seems to have changed.
Ensure Azure Pipelines is installed for your organization or repository
Edit your Azure DevOps Build (Pipeline)
Click on the Get sources step
Under the GitHub configuration, select Report build status
Save (& queue, if you wish) your updated configuration
If someone on the DevOps team sees this, reporting commit status should be enabled by default!
There isn’t such setting in VSTS, you can refer to this workflow to do it:
Get a commit sha
Create a status check context through REST API
Post: https://api.github.com/repos/[owner]/[repository]/statuses/[commit sha]
Body(application/json):
{
"state": "success",
"target_url": "XXX",
"description": "Build verify",
"context": "continuous-integration/vsts"
}
Then check the related status check in branch protect page:
Note: the target_url can be badge URL (Check Badge enabled in Options of build definition)
Create a build definition to create status through REST API (The same as step 2: change commit sha and body) in VSTS continuous integration (Enable continuous integration) for current commit
Create a build definition to update status of current commit through REST API in VSTS (Enable pull request validation)
From Jenkins, Pull-Request Status can be created/updated from pipeline
script {
pullRequest.createStatus(status: "success",
context: "validate-profiles",
description: "Profiles file validated successfully!",
targetUrl: "$RUN_DISPLAY_URL")
}
Tons of other things can be done from pipeline avoiding explicit calls to GitHub API
Make a comment on Pull-Request
pullRequest.comment("Your service-profile request is received. Please track ticket progress here: "+ticketData['_links']['web'])
Create & Add Labels to Pull-Request
pullRequest.addLabel(env.TICKET_ID)
Update Title for the Pull-Request
pullRequest.setTitle("["+env.TICKET_ID+"] Profile Review Request for "+env.CHANGE_TARGET)
I have created a single job in Jenkins to be triggered by commit on any branches in the GitHub using Webhook.
I want to create a custom workspace for each job trigger with respective to the branch commit.
I Tried following options and could not achieve it. Appreciate for any help.
Job Name : Test_Clone
Used advance options in general section and tried below options to name the workspace dynamically.
Test_Clone_${GIT_BRANCH} - always gives the branch name from previous build.
Test_Clone_${ref} - tried to use ref as defined in GitHub webhook payload, with no result.
To achieve: Ex: Commit from GitHub branch release-2.13.0, Jenkins should create workspace with name Test_Clone_release-2.13.0.
You might try and setup
first a payload variable in your Jenkins build, as described in "How to process a github webhook payload in Jenkins?"
then a webhook url (on GitHub side) of:
http://<<yourserver>>/job/<<yourjob>>/buildWithParameters?token=<<yourtoken>>
Then your Jenkins job would have the xml webhook payload in it, which you can analyze (with jq) and extract the 'ref' which includes the branch name.
From there, I would call (chain) a second job with a "branch" parameter (unless you can write a pipeline DSL with Jenkins 2) with that branch name, in order for the second job to use a custom workspace name based on that parameter