基于 yaml 管道资源的条件

Conditions based on resources on yaml pipeline

我有 2 个 Git 存储库:一个包含应用程序的源代码,一个用于 DevOps 管道。

对于管道的第二阶段,我想检查触发管道的分支是否为主。 但问题是变量 Build.SourceBranchName 有 DevOps 存储库的信息,而不是包含源代码的存储库(存储库名为 hidden ).

我没有看到任何可用于该目的的变量。

resources:
  repositories:
  - repository: 'hidden'
    type: git
    name: 'hidden/hidden'
    trigger:
    - master
    - develop

trigger: none

stages:
- stage: Build
  displayName: Build stage

  variables:
  - name: BuildConfiguration
    value: 'Release'
  - name: ApiSolution
    value: 'Company.WebApi.csproj'

  jobs:
  - job: BuildAPI
    displayName: 'Build API'

    pool:
      vmImage: 'ubuntu-latest'

    steps:
    - checkout: self
    - checkout: hidden

    - script: dir $(Build.SourcesDirectory)
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: 'env | sort'
[...] 

- stage: DeployDev
  displayName: 'Deploy dev stage'

  dependsOn: Build
  condition: and(succeeded(), eq(variables['Build.SourceBranchName'], 'master'))

  jobs:
  - deployment: DeployServiceApp
    displayName: 'Deploy system to the dev environment job'

    workspace:
      clean: all
      
    environment: 
      name: 'xyz'
      resourceType: 'VirtualMachine'

    strategy:
      runOnce:
        deploy:
          steps:
[...]

有人对此有解决方案吗?

我们可以添加任务bash和脚本printenv来打印所有环境变量,然后我找到了这个变量BUILD_SOURCEBRANCH,它是完整的触发器分支名称,例如refs/heads/master

结果:

此外,如果您在环境变量中找不到您需要的变量,我们可以添加 power shell 脚本并使用此 API 检查触发分支。

请尝试通过 $[ resources.repositories['other'].ref ] 获取详细信息,如图所示 here

我今天测试了这个,现在可以用了:

name: ref-name

trigger: none
pr: none

resources:
  repositories:
    - repository: devops
      type: github
      name: kmadof/devops-templates
      endpoint: kmadof
    - repository: azure
      type: git
      name: 'DevOps Manual/azure-functions'

variables:
  test: "true"
  azure.ref: $[ resources.repositories['azure'].ref ] 
  tools.ref: $[ resources.repositories['devops'].ref ] 
  isMain: $[eq(resources.repositories['devops'].ref, 'refs/heads/master')]

steps:
- checkout: self
- checkout: devops
- checkout: azure
- script: env | sort
  displayName: Print env variables
- bash: |
    echo "Tools version: $TOOLS_REF"
    echo "Tools version: $AZURE_REF"
    echo "Tools version: $ISMAIN"