扩展我的 Azure DevOps 管道以包括对所有拉取请求的构建验证

Extending my Azure DevOps Pipeline to include Build validation for all Pull Requests

我有 30 个左右 Java 运行 相同 ci 和 cd 模板的微服务。即我的每个微服务都有一个如下所示的构建管道,如下所示 运行s 在合并到 master 时自动:

name: 0.0.$(Rev:r)

trigger: 
  - master
pr: none 

variables:
- group: MyCompany

resources:
  repositories:
    - repository: templates
      type: git
      name: <id>/yaml-templates

stages:
  - stage: Build
    jobs:
    - job: build
      displayName: Build
      steps:
      - template: my-templates/ci-build-template.yaml@templates
  - stage: PushToContainerRegistry
    dependsOn: Build
    condition: succeeded()
    jobs:
    - job: PushToContainerRegistry
      displayName: PushToContainerRegistry
      steps:
      - template: my-templates/ci-template.yaml@templates

其中 ci-build-template.yaml 包含...

steps:
  - checkout: self
    path: s 

  - task: PowerShell@2

  - task: Gradle@2
    displayName: 'Gradle Build'

  - task: SonarQubePrepare@4
    displayName: SonarQube Analysis

  - task: CopyFiles@2
    displayName: Copy build/docker to Staging Directory

我想在有人提出 pr 合并到 master 时实施 pr 构建验证。在 PR 构建中,只有构建阶段应该 运行 并且构建模板中只有 ci-build-template.yaml 中的一些任务应该 运行.

我学习的几个问题:

如果是 pr 构建,我如何提升上面的 yaml 管道以跳过“PushToContainerRegistry”?

如果是 pr 构建,我如何提升 ci-build-template.yaml 来跳过“SonarQubePrepare@4”和“CopyFiles@2”?

最后,我如何提升上面的 yaml 管道,以便为所有目标分支为 master 的 pr 启用构建验证?

在做我自己的研究时,我知道你可以通过 clickops 做到这一点,但我一直在学习如何通过 yaml 实施。

谢谢

How can i uplift the yaml pipeline above to make the "PushToContainerRegistry" skip if it is a pr build?

How can i uplift ci-build-template.yaml to make the "SonarQubePrepare@4" and "CopyFiles@2" skip if it is a pr build?

只需要使用任务条件:

例如,

pool:
  name: Azure Pipelines
steps:
- script: |
   echo Write your commands here
   
   echo Hello world
   
   echo $(Build.Reason)
  displayName: 'Command Line Script'
  condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))

如果 Pull 请求触发管道,以上定义将跳过该步骤。

请参考这些文档:

https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#using-the-trigger-type-in-conditions

https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services

And lastly how can i uplift the yaml pipeline above to enable build validation for all pr's that have a target branch of master?

您可以在条件中使用这个表达式:

eq(variables['System.PullRequest.TargetBranch'], 'refs/heads/master')

如果你是基于 DevOps git repo,那么只需要添加分支策略就可以了:

https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops&tabs=browser#configure-branch-policies