我有三级嵌套的 Azure DevOps yaml 模板。在我的第二级嵌套模板中,我想根据拉取请求的目标分支有条件地调用第三级模板。
例如仅当拉取请求目标分支是 Main 时才应调用 level3@templates。
我知道 System.PullRequestTargetBranch 在模板中不可用。我也很熟悉
以及预定义变量对嵌套模板的限制
我希望有人能够提出一些解决方法来解决这个问题。
感谢所有帮助。
我的yaml结构如下
resources:
repositories:
- repository: templates
type: git
name: MyProj/templates
ref: refs/heads/main
extends:
template: extends/level1.yaml@templates
parameters:
MY_STAGES:
BUILD:
displayName: "Build"
L1Config:
config1: "config1"
parameters:
- name: MY_STAGES
type: object
default: {}
- name: L1Config
type: object
default: {}
variables:
- name: var1
value: "value1"
- name: var2
value: "val2"
stages:
- ${{ each MY_STAGE in parameters.MY_STAGES }}:
- stage: ${{ MY_STAGE.key }}
displayName: "Build"
jobs:
- job: build_dev
displayName: Build
steps:
- template: /jobs/level2@templates
parameters:
L2Config: ${{ MY_STAGE.value.L1Config }}
parameters:
- name: L2Config
type: object
default: {}
steps:
- pwsh: Write-Host "Hello World!"
# This is the template I want to call conditionally, based on the PullRequest Target
- ${{ if eq(variable['System.PullRequest.TargetBranch'], 'refs/heads/main') }}:
# I know above syntax does not work, I have just written it down as an example of what I wish had worked.
- template: /steps/level3@templates
parameters:
param1: value1
正如你所说,System.PullRequest.TargetBranch 和 System.PullRequest.SourceBranch 无法在编译时扩展。
没有现成的方法可以完全满足您的要求。 If 表达式无法获取 Pull Request Branch 的正确值。
您可以参考以下方法:
您可以将 Pipeline 拆分为两个 Pipeline。第一个 Pipeline 将用于获取 System.PullRequest.TargetBranch,然后使用 Powershell 脚本将值传递给第二个 Pipeline 中的参数值。
这是一个例子:
第一条管道:
pool:
vmImage: windows-latest
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$token = "$(pat)"
$url="https://dev.azure.com/{Orgname}/{Projectname}/_apis/pipelines/{PipelineRunID}/runs?api-version=5.1-preview"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = "
{
`"resources`": {
`"repositories`": {
`"self`": {
`"ref`": `"refs/heads/main`"
}
}
},
`"templateParameters`": {
`"PullRequestref`":`"$(System.PullRequest.TargetBranch)`"
},
}"
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json
第二条管道:
主要
resources:
repositories:
- repository: templates
type: git
name: MyProj/templates
ref: refs/heads/main
parameters:
- name: PullRequestref
type: string
default: refs/heads/test
extends:
template: extends/level1.yaml@templates
parameters:
MY_STAGES:
BUILD:
displayName: "Build"
L1Config:
config1: "config1"
2级:
parameters:
- name: L2Config
type: object
default: {}
steps:
- pwsh: Write-Host "Hello World!"
- ${{ if eq(parameters.PullRequestref, 'refs/heads/main') }}:
- template: /steps/level3@templates
parameters:
param1: value1