Azure DevOps Pipeline中AzureCLI@2输出无法作为变量使用的问题
问题原因与解决方案
你遇到的问题核心在于:AzureCLI@2任务不会自动将az命令返回的JSON结果映射为任务的输出变量——哪怕你给任务设置了name: myOutput,这个名称只是用来标识任务,并不会帮你自动解析提取JSON里的字段。要让后续任务能引用这些值,你需要在脚本里显式地把需要的字段通过Azure Pipelines的变量设置命令输出。
具体修改步骤
1. 调整AzureCLI任务的内联脚本
在你的inlineScript里,先把az命令的结果转换为PowerShell的JSON对象,然后用##vso[task.setvariable]命令把需要的字段设置为输出变量(必须加上isOutput=true参数,这样才能被其他任务识别为可引用的输出)。
修改后的完整任务配置如下:
- task: AzureCLI@2 displayName: 'List info on read policy in DEV' name: myOutput inputs: azureSubscription: mySub scriptType: ps scriptLocation: inlineScript inlineScript: | # 执行az命令并将JSON输出转换为PowerShell对象 $ruleKeys = az servicebus topic authorization-rule keys list --resource-group myRG --namespace-name mySB --topic-name myTopic --name Listen | ConvertFrom-Json # 将需要的字段设置为输出变量 Write-Host "##vso[task.setvariable variable=primaryConnectionString;isOutput=true]$($ruleKeys.primaryConnectionString)" Write-Host "##vso[task.setvariable variable=secondaryConnectionString;isOutput=true]$($ruleKeys.secondaryConnectionString)" Write-Host "##vso[task.setvariable variable=primaryKey;isOutput=true]$($ruleKeys.primaryKey)" Write-Host "##vso[task.setvariable variable=secondaryKey;isOutput=true]$($ruleKeys.secondaryKey)"
2. 后续任务引用变量的方式
同一Job内的引用
如果后续任务和这个AzureCLI任务在同一个Job里,直接用你原本期望的格式$(myOutput.primaryConnectionString)就能拿到值了。比如:
- script: | echo "Primary Connection String: $(myOutput.primaryConnectionString)" echo "Primary Key: $(myOutput.primaryKey)" displayName: 'Use Service Bus keys'
跨Job的引用
如果后续任务在另一个独立的Job中,需要先在产出变量的Job里声明输出,再依赖这个Job进行引用:
jobs: - job: FetchServiceBusKeys steps: - task: AzureCLI@2 name: myOutput # 上面的完整配置... outputs: primaryConnStr: $(myOutput.primaryConnectionString) primaryKeyVal: $(myOutput.primaryKey) - job: ProcessWithKeys dependsOn: FetchServiceBusKeys variables: targetConnStr: $[ dependencies.FetchServiceBusKeys.outputs['primaryConnStr'] ] targetKey: $[ dependencies.FetchServiceBusKeys.outputs['primaryKeyVal'] ] steps: - script: echo "Using connection string: $(targetConnStr)" displayName: 'Consume cross-job variables'
为什么原来的方法不生效?
Azure Pipelines的任务输出变量不是自动生成的——除非任务本身有内置的输出(比如某些打包任务会输出包路径)。对于AzureCLI任务来说,它只会执行你给定的脚本,不会主动解析脚本的输出内容并生成变量,必须通过##vso[task.setvariable]命令明确告知流水线要把某个值作为输出变量暴露出去。
内容的提问来源于stack exchange,提问作者Christer Berglund
相关产品推荐
相关产品推荐

