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

Posted

技术标签:

【中文标题】从脚本返回对象变量 - Azure YAML 管道【英文标题】:Return an object variable from a script - Azure YAML pipelines 【发布时间】:2021-04-02 10:12:36 【问题描述】:

考虑以下简化的管道:

### 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】:

作为一种解决方法,我们可以创建另一个管道。在这个管道中,我们添加了两个 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管道,得到结果:

【讨论】:

以上是关于从脚本返回对象变量 - Azure YAML 管道的主要内容,如果未能解决你的问题,请参考以下文章

Azure DevOps YAML 管道从传递的变量中删除引号和双反斜杠

Azure Devops - 将 YAML 脚本中的变量设置为日期时间

azure devops yaml管道未设置变量

如何在 yaml 中处理 Azure DevOps 管道中的错误?

使用“扩展”的 Azure yaml 管道

如何使用 Azure REST API 从管道中获取所有变量?