Azure DevOps:确保生产阶段只能从存储库的主分支发布

pad*_*ike 5 devops azure-devops azure-pipelines

我有一个包含通常阶段的发布管道

开发 -> 测试 -> 预生产 -> 生产

我想知道是否有一种方法可以确保只有主分支可以一直升级到生产,以避免从功能发布和开发分支在生产环境中结束。

bry*_*ook 7

YAML 管道

如果您使用基于 YAML 的管道,则可以使用检查 + 批准门功能来添加分支策略检查。

  1. 为每个部署环境创建一个环境
  2. 构建 YAML 管道以使用指定环境的部署作业
stages:
- stage: build
- stage: dev
- stage: test
- stage: preprod
- stage: prod
Run Code Online (Sandbox Code Playgroud)

您可以在阶段上放置条件以确保满足分支条件。

- stage: production
  dependsOn: preprod
  condition: |
    and(
      succeeded('preprod'),
      or(
        eq(variables['Build.SourceBranch'], 'refs/heads/main'),
        startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'),
        startsWith(variables['Build.SourceBranch'], 'refs/heads/hotfix/')
      )         
    )
Run Code Online (Sandbox Code Playgroud)
  1. 确保执行部署活动的每个阶段都有一个部署作业
- deployment: deploy
  displayName: 'Deploy'
  environment: 'Production'
  strategy:
    runonce:
      deploy:
        steps:
        - pwsh: Write-Host 'Deployment Steps go here!'
Run Code Online (Sandbox Code Playgroud)
  1. 在您的生产环境中,添加分支控制检查

    分支控制

经典发布管道

如果您使用的是经典发布管道,则可以添加工件过滤器以防止管道排队,但这并不强制阶段无法手动运行或覆盖这些过滤器。

如果您确实想阻止发布,即使有人手动覆盖工件过滤器,您也可能通过检查它是否是脚本中的正确分支来使构建失败。

$currentBranch = "$(Release.Artifacts.MyAlias.SourceBranch)" 
if ( $currentBranch -ne "refs/heads/main" )
{
    Write-Host "##vso[task.logissue type=error]This release must originate from the main branch. Current branch: $currentBranch"
    Exit 1
}
Run Code Online (Sandbox Code Playgroud)

构建脚本失败