从脚本返回对象变量 - Azure YAML 管道

时间:2020-12-23 19:55:05

标签: azure azure-devops yaml azure-pipelines azure-pipelines-yaml

考虑以下简化的管道:

### template.yml ###
parameters:
  - name: "tables"
    type: object
    default: {}
 
steps:
  - ${{ each table in parameters.tables }}:
      - task: BackupTask@0
        displayName: "Backup ${{ table }}"
### pipeline.yml ###
- template: template.yml
  parameters:
    tables:
      - "table1"
      - "table2"
      - "table3"
      - "table4"
      - "table5"

我想要的是表格列表是使用 bash 脚本生成的,而不必手动编写它们。因此,每次创建新表时,管道都会自动对其进行备份。

1 个答案:

答案 0 :(得分:0)

作为一种解决方法,我们可以创建另一个管道。在这个管道中,我们添加了两个 powershell 任务。在第一个任务中,我们设置了一个以表格为值的变量。

- task: PowerShell@2
     inputs:
       targetType: 'inline'
       script: 'Write-Host "##vso[task.setvariable variable=list]table1,table2,table3"'

在第二个任务中,我们使用 rest api 来触发 pipeline.yml 管道。在请求体中,我们使用第一个任务中设置的变量作为模板参数的值。

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $token = "PAT"
      $url="https://dev.azure.com/{org}/{pro}/_apis/pipelines/{pipelineId}/runs?api-version=5.1-preview"
      $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
      
      $JSON = @'
      {
        "templateParameters": {
          "tab":"[$(list)]"
         },
      }
      '@
      
      $response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json

以下是我的测试样本:

### pipeline.yml ###
parameters:
  - name: tab
    type: object
    default: {}

pool:
  vmImage: 'ubuntu-latest'

steps:  
- template: template1.yml
  parameters:
    tables: ${{ parameters.tab }}

模板.yml:

### template1.yml ###
parameters:
  - name: "tables"
    type: object
    default: {}
 
steps:
   - ${{ each table in parameters.tables }}:
      - task: PowerShell@2
        inputs:
          targetType: 'inline'
          script: echo "${{ table }}"

然后我们运行新创建的管道来触发pipeline.yml管道,得到结果:

enter image description here

相关问题