Azure DevOps Pipeline模板阶段依赖与变量传递问题求助
解决方案
要实现Cleanup阶段在ImageDeployment、build_functionapp_testcase2、datafactory_testcase3任一阶段失败时运行,同时获取ImageDeployment的NEW_VERSION变量,可按以下方式修改Pipeline:
关键改动说明
- 引用模板阶段时显式指定阶段名称,解决无法在
dependsOn中引用模板阶段的问题 - 调整Cleanup阶段的
dependsOn和condition,覆盖所有需要触发清理的场景 - 保留原有的输出变量引用逻辑,确保能获取到ImageDeployment生成的版本号
修改后的Pipeline代码
- stage: ImageDeployment jobs: - job: NewImageDeployment timeoutInMinutes: 180 pool: vmImage: 'ubuntu-latest' steps: - task: AzureKeyVault@2 displayName: 'Fetch Secrets' inputs: connectedServiceName: '$(GLOBAL_SERVICE_CONNECTION)' keyVaultName: $(GLOBAL_KV_NAME) secretsFilter: "Packer-Secret" runAsPreJob: false - task: AzureCLI@2 displayName: 'Check image version' retryCountOnTaskFailure: 0 inputs: azureSubscription: '$(GLOBAL_SERVICE_CONNECTION)' scriptType: 'bash' scriptLocation: 'inlineScript' inlineScript: | while IFS=$' ' read -a arr_image_versions; do version=${arr_image_versions[0]} date=${arr_image_versions[1]} if [[ $date > $old_date ]]; then last_version=$version fi old_date=$date done <<< "$(az sig image-version list --gallery-image-definition xxxxxxxxxxx --gallery-name xxxxxxx --resource-group xxxxxxxx --query "[].[name, publishingProfile.publishedDate]" -o tsv)" echo "Last image version: $last_version" echo "##vso[task.setvariable variable=last_version]$last_version" - task: Bash@3 name: CheckImageVersion displayName: 'Increment image version' inputs: targetType: 'inline' script: | IFS='.' read -ra VERSION_PARTS <<< "$(last_version)" PATCH_VERSION=${VERSION_PARTS[2]} PATCH_VERSION=$((PATCH_VERSION + 1)) NEW_VERSION="${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.$PATCH_VERSION" echo "New image version: $NEW_VERSION" echo "##vso[task.setvariable variable=NEW_VERSION;isOutput=true]$NEW_VERSION" # 引用模板时显式指定阶段名称 - template: tests/build_functionapp_testcase2.yaml@self name: BuildFunctionApp - template: tests/datafactory_testcase3.yaml@self name: DataFactoryTest - stage: Cleanup # 依赖所有需要监控的阶段 dependsOn: - ImageDeployment - BuildFunctionApp - DataFactoryTest # 任一依赖阶段失败时触发 condition: or(failed('ImageDeployment'), failed('BuildFunctionApp'), failed('DataFactoryTest')) jobs: - job: DeleteImage pool: vmImage: 'ubuntu-latest' variables: # 依旧从ImageDeployment阶段获取输出变量 NEW_VERSION: $[ stageDependencies.ImageDeployment.NewImageDeployment.outputs['CheckImageVersion.NEW_VERSION'] ] steps: - script: | echo "NEW_VERSION in Cleanup stage: $(NEW_VERSION)"
注意事项
- 显式指定的阶段名称(
BuildFunctionApp、DataFactoryTest)可根据实际需求调整,只要确保唯一即可 - 即使ImageDeployment阶段成功,但其他两个模板阶段失败,Cleanup仍会触发,且能正常获取到
NEW_VERSION变量 - 若模板文件中定义了多个阶段,此方法同样适用,每个引用的模板阶段都会被赋予指定名称
内容的提问来源于stack exchange,提问作者Sumit Bhardwaj
相关产品推荐
相关产品推荐

