I am trying to find the configuration required for using VSTS external services to make a VSTS release required to be successful before the PR to master can be completed.
The workflow is:
Create PR -> Triggers Build -> On Success Triggers Release -> On Success will flag the PR as OK.
Is there a way to do this using external services to post a successful status?
For the release definition, you can triggerred by the PR validation build artifacts, so you can get the pull request id by the pre-definied variable Release.Artifacts.{alias}.SourceBranch.
Assume the artifact alias for the release definition is prvalid, then you can get the pull request id (as the variable $id below) with below script:
$id="$(Release.Artifacts.prvalid.SourceBranch)".Split('/')
echo $id
$id=$id[2]
And then you can get the source branch and target branch by the REST API:
GET https://acount.visualstudio.com/DefaultCollection/_apis/git/repositories/repoID/pullRequests/PRid?api-version=3.0
Then you can merge the source branch into tartget branch, and the PR status will be completed.
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.
I'm looking on a way to trigger a Azure pipeline ONLY on successful (or attempted) pull request merge.
Now I have :
trigger:
branches:
include:
- DEV
steps:
- script: FOO
But this runs EVERY time there is a change on the DEV branch and I would like to avoid that.
Besides, I want a programmatic response not going trough the UI each time.
EDIT:
A weird thing is happnening
condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
gets:
Expanded: and(True, eq('IndividualCI', 'PullRequest'))"
When doing a PR, and thus doesn't work as intented
I'm looking on a way to trigger a Azure pipeline ONLY on successful (or attempted) pull request merge.
There is no such out of box way to achieve this at this moment.
We could only set the CI trigger on the target branch, but we could set the condotion for the pipeline to avoid build any task:
and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
For example:
trigger:
branches:
include:
- DEV
steps:
- script: FOO
condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
Or you could set the condition for the stage, job and so on.
Please check the document Specify conditions for some more details.
If there is a change on the DEV branch and it would be avoided by the condition.
Note: With above way, the pipeline will be triggered, but no task will be executed.
And if you even do not want the pipeline be triggered. You could add new pipeline with powershall task to invoke REST API to trigger above pipeline and set the condition to the powershell task.
In this way, the pipeline will only triggered when the commit comes from the PR.
Update:
Doing a PR on the DEV branch results in : "Expanded: and(True,
eq('IndividualCI', 'PullRequest'))"
Yes,you are correct. That because azure devops does not have the feature to trigger the pipeline after the PR completed. Pull request trigger and Build Validation both trigger the pipeline when the PR starts.
To resolve this request, we could try create a service hook to monitor PR status. If the PR status changes, the pipeline is triggered through API or Application, you could check this document for some more details.
And another way to achieve is using the REST API.
The main idea is:
create a pipeline and set it as Build validation, but not set it as Required, should set it as Optional:
Add powershell task in above pipeline to invoke REST API to monitor the PR status until it complated, and add another task to invoke the REST API to trigger your current pipeline.
So, you could remove the:
trigger:
branches:
include:
- DEV
in your current pipeline.
The trigger you have set is a CI trigger, it will work whenever the target branch has a new commit.
Currently, there isn't a trigger that works when a pull request is completed.
The feature closest to your needs is PR triggers and build validation branch policy.
They will work when a pull request is created or when it has been changed.
If you are using Azure Repos Git, please use branch policy for build validation. If you are using GitHub or Bitbucket Could, please use pr triggers. Click the documents for the detailed information.
Besides, you can use branch policy to prevent the direct commits. When you set the branch policy of any type, only users with "Bypass policies" permission can commit to the branch directly. The rest of the users must commit the branch through a pull request.
How to create branch policy: Branch policies and settings.
How to set "Bypass policies" permission: Set Git repository permissions.
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 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 GHPRB jenkins job which is trigger when i create pull request in my git repository.
I want to stop triggering job when my pull request is in conflicts state. Or my jenkins job will populate proper message for same.
What should i do for same
Thanks