有条件地设置环境 Azure DevOps

Conditionally Set Environment Azure DevOps

我正在使用 Azure Pipeline,我需要在其中有条件地设置 environment 属性。我通过在正文 which is documented here. 中传递 Parameters 从休息 API 调用调用管道。当我尝试在编译时访问那个 parameter 以有条件地设置环境时,尽管变量是空的(假设它在编译时不可访问?)

有人知道通过管道或 API 调用解决此问题的好方法吗?

这是 YAML 管道的一个常见混淆区域。 运行-时间变量需要使用不同的语法来访问。

$[ variable ]

YAML 管道经历几个阶段。

  1. 编译 - 这是将构成最终管道的所有 YAML 文档(模板等)编译成单个文档的地方。使用 ${{}} 语法的参数和变量的最终值被插入到文档中。
  2. 运行time - 运行-插入使用 $[] 语法的时间变量。
  3. 执行 - 最终管道由代理 运行。

这是一个简化,微软的另一个解释更好一点:

  1. First, expand templates and evaluate template expressions.
  2. Next, evaluate dependencies at the stage level to pick the first stage(s) to run.
  3. For each stage selected to run, two things happen:
    • All resources used in all jobs are gathered up and validated for authorization to run.
    • Evaluate dependencies at the job level to pick the first job(s) to run.
  4. For each job selected to run, expand multi-configs (strategy: matrix or strategy: parallel in YAML) into multiple runtime jobs.
  5. For each runtime job, evaluate conditions to decide whether that job is eligible to run.
  6. Request an agent for each eligible runtime job.

...

This ordering helps answer a common question: why can't I use certain variables in my template parameters? Step 1, template expansion, operates solely on the text of the YAML document. Runtime variables don't exist during that step. After step 1, template parameters have been resolved and no longer exist.

[参考:https://docs.microsoft.com/en-us/azure/devops/pipelines/process/runs?view=azure-devops]

经过一番挖掘,我找到了问题的答案,希望这对以后的其他人有所帮助。

事实证明 Build REST API 确实支持可在编译时使用的模板参数,文档只是没有明确告诉您。 Runs 端点也支持此功能。

我请求的负载最终看起来像:

{
    "Parameters": "{\"Env\":\"QA\"}",
    "templateParameters": {"SkipApproval" : "Y"},
    "Definition": {
        "Id": 123
    },
    "SourceBranch": "main"
}

并且我的管道在编译时通过管道的以下(缩写版本)消耗了这些更改

parameters:
  - name: SkipApproval
    default: ''
    type: string
...
        ${{if eq(parameters.SkipApproval, 'Y')}}: 
            environment: NoApproval-All
        ${{if ne(parameters.SkipApproval, 'Y')}}:
            environment: digitalCloud-qa