如何在 Azure DevOps 管道的 for 循环中使用定义的变量?

How to use defined variables in the for loop in Azure DevOps pipeline?

我想以递归方式将所有包发布为 Azure DevOps 管道中 $(Build.ArtifactStagingDirectory) 文件夹中的通用包。因此,我遍历了用户定义的变量,该变量是作为先前 bash 脚本的输出而创建的。然后,我使用 UniversalPackages@0 任务通过 for 循环发布一个包。

           - bash: |
                #!/bin/bash

                get_all_files=$(ls -Rp '$(Build.ArtifactStagingDirectory)' | grep -v /)

                my_array=()

                for OUTPUT in $get_all_files
                do
                file_name="${OUTPUT##*/}"
                echo "File: $file_name"
                my_array[${#my_array[@]}]=$file_name
                done
                my_array=${my_array[@]}
                echo "##vso[task.setvariable variable=my_array;isOutput=true]$my_array"
            displayName: 'Get the list of packages'
            name: setVarStep

          - bash: echo $(setVarStep.my_array)
            displayName: 'List the packages'

          - ${{ each item in '$(setVarStep.my_array)' }}:
            - task: UniversalPackages@0
              displayName: Universal Publish
              inputs:
                command: publish
                publishDirectory: '$(Build.ArtifactStagingDirectory)'
                vstsFeedPublish: 'my-feed'
                vstsFeedPackagePublish: $(item)
                packagePublishDescription: 'Publish package'

管道抛出以下错误。

Expected a sequence or mapping. Actual value '$(setVarStep.my_array)'

看起来这不是使用在 运行 时间定义的变量的正确方法。如何在 Azure DevOps 管道的 for 循环中使用定义的变量?

${{ }} 语法在模板执行之前进行评估。因此,该值在那个时间点实际上是未定义的。在模板扩展期间不能依赖运行时值。

您可以使用命令行工具通过 Azure DevOps CLI. It has a az artifacts universal publish command:

从您的脚本块直接发布到工件
// If not installed by default in Azure CLI
az extension add --name azure-devops

export AZURE_DEVOPS_EXT_PAT=$(System.AccessToken)
az devops login --organization https://dev.azure.com/jessehouwing/
az artifacts universal publish --organization https://dev.azure.com/jessehouwing/ --feed feed-name --name my-first-package --version 0.0.1 --description "Welcome to Universal Packages" --path .

它需要安装 Azure CLI 和 Azure CLI DevOps 插件。在托管代理上,我认为这是默认设置。

我不是 100% 确定您可以使用 the predefined SYSTEM_ACCESSTOKEN 作为 PAT。

- bash: echo This script could use $SYSTEM_ACCESSTOKEN
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)

我猜这最终应该会起作用,UniversalPackages 任务中使用的就是这个标记。