如何在 Azure Pipelines 的每个阶段使用不同的服务连接?

Her*_*des 8 yaml azure-devops azure-pipelines

在 Azure Pipelines 中使用来自 yaml 的多级管道并且每个阶段都将资源部署到单独的环境时,我想为每个阶段使用专用服务连接。就我而言,每个阶段都使用相同的部署作业,即 yaml 模板。所以我使用了很多具有依赖于环境的特定值的变量。这工作正常,除了服务连接。

理想情况下,包含服务连接名称的变量被添加到阶段级别,如下所示:

stages:
- stage: Build
    # (Several build-stage specific jobs here)

- stage: DeployToDEV
  dependsOn: Build
  condition: succeeded()
  variables:
    AzureServiceConnection: 'AzureSubscription_DEV' # This seems like a logical solution
  jobs:
    # This job would ideally reside in a yaml template
    - job: DisplayDiagnostics
      pool:
        vmImage: 'Ubuntu-16.04'
      steps:
        - checkout: none
        - task: AzurePowerShell@4
          inputs:
            azureSubscription: $(AzureServiceConnection)
            scriptType: inlineScript
            inline: |
              Get-AzContext
            azurePowerShellVersion: LatestVersion

- stage: DeployToTST
  dependsOn: Build
  condition: succeeded()
  variables:
    AzureServiceConnection: 'AzureSubscription_TST' # Same variable, different value
  jobs:
    # (Same contents as DeployToDEV stage)
Run Code Online (Sandbox Code Playgroud)

执行此代码段时,会产生错误消息:

存在资源授权问题:“管道无效。作业显示诊断:步骤 AzurePowerShell 输入 ConnectedServiceNameARM 引用了无法找到的服务连接 $(AzureServiceConnection)。服务连接不存在或未被授权使用。用于授权详情请参考https://aka.ms/yamlauthz

因此,当运行开始时,它可能无法足够快地扩展变量 AzureServiceConnection。但如果确实如此,那么为每个阶段使用单独的服务连接的替代解决方案是什么?

一个肯定有效的选项是将服务连接名称直接设置为所有任务,但这将涉及为每个阶段复制相同的 yaml 任务,我显然想避免这种情况。

任何人都有这方面的线索?提前致谢!

Ven*_*ala 8

目前您不能将变量作为 serviceConnection 传递。显然,服务连接名称是在推送/提交时获取的,并且将获取任何内容。

例如,如果您有 $(variable) 它将选择 $(variable) 而不是值。

到目前为止,我使用的解决方法是对每个阶段的步骤使用模板,并通过 serviceConnection 传递不同的参数。

有关示例实现,请参阅:https : //github.com/venura9/azure-devops-yaml/blob/master/azure-pipelines.yml。非常欢迎您提出更新请求。

- stage: DEV
  displayName: 'DEV(CD)'
  condition: and(succeeded('BLD'), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))
  dependsOn: 
   - BLD
  variables: 
    stage: 'dev'
  jobs:

  - job: Primary_AustraliaSouthEast
    pool:
      vmImage: $(vmImage)
    steps:
    - template: 'pipelines/infrastructure/deploy.yml'
      parameters: {type: 'primary', spn: 'SuperServicePrincipal', location: 'australiasoutheast'}
    - template: 'pipelines/application/deploy.yml'
      parameters: {type: 'primary', spn: 'SuperServicePrincipal'}
Run Code Online (Sandbox Code Playgroud)