I am trying to resolve my issue with Azure DevOps Pipeline. My pipeline works based on the branch from which the changes were triggered. In this way when the changes comes from the for example release
branch it download release
branch from repository. The same way I want to test changes coming from the PR before merge to main branch. When the tests are accepted then we can approve PR.
Originally my stage for those changes looks like that:
resources:
repositories:
[rest of the code]
stages:
- stage: COIN_DEV
displayName: Coin dev
dependsOn: Validation
condition: startsWith(variables['sourceBranch'], 'refs/pull/')
jobs:
- deployment: DeployTo_COIN_DEV
displayName: Deploy to DEV
[rest of the code]
If your Git repository is on Azure DevOps, you should set the PR trigger via Build Validation of branch policies for the target branch. For your case, since you need to use the PR to merge changes to main branch (the target branch of PR), the branch policies need to ne set on the main branch. For more details, see "PR triggers in Azure Repos Git".
In the YAML pipeline you have set as Build Validation on the policies for main branch, if you want a stage can run only when the pipeline is triggered by PR, you can configure the pipeline like as below:
Ensure the pipeline main YAML file with this configuration is always existing on the latest code version of the source branch of PR, so the YAML can be applied to the Build Validation of PR. For example, a PR is created to merge changes from release
branch (source branch) to main
branch (target branch), the YAML file must be always existing on the release
branch.
. . .
stages:
- stage: PR
displayName: 'Run for Pull Request'
condition: startsWith(variables['Build.SourceBranch'], 'refs/pull/')
jobs:
- job: build
steps:
# Check out the code files from PR.
- checkout: self
displayName: 'Checkout code from $(Build.SourceBranch)'
- script: |
echo "Build.Reason = $(Build.Reason)"
echo "Build.SourceBranch = $(Build.SourceBranch)"
echo "Build.SourceVersion = $(Build.SourceVersion)"
echo "Build.SourceVersionMessage = $(Build.SourceVersionMessage)"
displayName: 'Show Information'
# Steps to build and test the code checked out from PR.
. . .
If your Git repository is on other platforms, such as GitHub or Bitbucket, you can directly set the PR trigger in the pipeline main YAML file.
# Set PR trigger.
# Trigger the pipeline when the target branch of PR is main.
pr:
- main
. . .
You also need to ensure the pipeline main YAML file is always existing on the latest code version of the PR source branch.