如何在 Azure DevOps yaml 管道中的每个循环中使用变量

Ear*_*Gen 6 powershell azure-devops azure-pipelines

我的 Azure DevOps 管道中有一个 PowerShell 脚本:

- task: PowerShell@2
  displayName: Get_records
  inputs:
    targetType: 'inline'
    script: |
        <...>
        $records.Records
Run Code Online (Sandbox Code Playgroud)

$records.Records是一些包含记录数组的变量。我需要以这种方式使用这些数据:对于该数组中的每条记录,我需要在一项作业中执行多项任务。像这样的东西:

stages:
- stage: stage_1
  jobs:
  - job: Job_1

    - task: PowerShell@2
      displayName: Get_records
      inputs:
        targetType: 'inline'
        script: |
          <..getting this records..>
          $records.Records

    - ${{each records in variables.records.Records}}:

      - task: not_powershell
        displayName: name1
        inputs:
          AsyncOperation: true
          MaxAsyncWaitTime: '60'
    
      - task: not_powershell
        displayName: name2
        inputs:
          AsyncOperation: true
          MaxAsyncWaitTime: '60'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?对此有几个问题:

  1. 如何在 foreach 循环中使用 '$records.Records' 变量?使用前必须保存变量吗?如果是 - 如何保存数组?
  2. 如果不可能这样做,可能有一些方法,例如使用多个阶段、作业...等?

Vin*_*ren 14

不,你不能。它仅适用于参数,不适用于变量:

您可以使用each关键字循环遍历参数

这是因为:

  • 在运行之前,yaml 被解析并编译成管道结构,其中定义了所有阶段、作业和任务。这是评估循环条件的点,并且循环扩展到多个阶段/作业/任务。
  • 动态运行时变量在编译时尚不可用,因此此时不能使用它们来定义each 循环。
  • 在运行时,当动态变量可用时,管道结构已经固定,因此此时不可能添加额外的任务。

解决方法

不能在管道中循环动态数组变量;但您可以这样做的一个地方是在任务中,例如在powershell 脚本中:

- task: PowerShell@2
  displayName: Loop Over Records
  inputs:
    targetType: 'inline'
    script: |
      # first, get the records
      ForEach ($record in $records.Records) {
        # do something with $record
      }
Run Code Online (Sandbox Code Playgroud)

这不像管道循环那么强大,可以使用所有不同类型的非 powershell 任务,但它可能是循环该数组的唯一方法。

  • 由于不同的原因它不起作用。`each` 可以与变量一起使用,您可以在 [`split`](https://learn.microsoft.com/en-us/azure/devops/pipelines/process/ 下链接的同一表达式页面上找到示例)表达式?view=azure-devops#split)。它不起作用的原因是因为 `${{}}` 是一个“编译时表达式”(请参阅​​顶部附近的相同表达式页面),它仅适用于该“编译时”可用的变量,因此它不能与任务创建的变量一起使用。 (3认同)