Azure Pipeline部署作业与常规作业间变量共享报错排查
部署作业与常规作业间共享Azure Pipeline变量时的"echo is off"问题及解决方法
我尝试在Azure Pipeline的部署作业和常规作业间共享变量,执行打印变量操作时出现了"echo is off"错误,同时想了解如何正确实现两类作业间的变量共享。
原YAML配置
stages: - stage: Stage jobs: - deployment: Staging displayName: Stage the WebApp environment: name: 'Windows10' resourceName: Lxxxxxx resourceType: virtualMachine strategy: runOnce: deploy: steps: - powershell: echo "##vso[task.setvariable variable=myStageOutputVar;isOutput=true]variable" name: printvar - stage: Swap dependsOn: Stage variables: myVarfromStage: $[ stageDependencies.Stage.Staging.outputs['Windows10.printvar.myStageOutputVar'] ] jobs: - deployment: Production displayName: Swap to production environment: name: 'Windows10' resourceName: Lxxxxxx resourceType: virtualMachine strategy: runOnce: deploy: steps: - script: echo $(myVarfromStage)
运行日志
Starting: CmdLine ============================================================================== Task : Command line Description : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows Version : 2.231.1 Author : Microsoft Corporation Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/command-line ============================================================================== Generating script. Script contents: shell echo ========================== Starting Command Output =========================== "C:\WINDOWS\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "C:\xxxxx\xxxxx\xxxxx\xxxxxxx\xxxxxxxxxxxx.cmd"" ECHO is off. Finishing: CmdLine
问题原因
出现"echo is off"是因为变量$(myVarfromStage)未正确获取到值,导致cmd执行空的echo命令,而系统默认echo状态为off时就会输出该提示。
错误根源在于部署作业输出变量的引用路径错误:部署作业的输出变量属于作业内的步骤,无需添加环境名称Windows10,原配置中多了环境名称前缀,导致无法正确解析变量值。
修正后的YAML配置
stages: - stage: Stage jobs: - deployment: Staging displayName: Stage the WebApp environment: name: 'Windows10' resourceName: Lxxxxxx resourceType: virtualMachine strategy: runOnce: deploy: steps: - powershell: echo "##vso[task.setvariable variable=myStageOutputVar;isOutput=true]variable" name: printvar - stage: Swap dependsOn: Stage variables: # 移除环境名称前缀,直接引用步骤名.变量名 myVarfromStage: $[ stageDependencies.Stage.Staging.outputs['printvar.myStageOutputVar'] ] jobs: - deployment: Production displayName: Swap to production environment: name: 'Windows10' resourceName: Lxxxxxx resourceType: virtualMachine strategy: runOnce: deploy: steps: - script: echo $(myVarfromStage)
部署作业与常规作业间共享变量的正确步骤
- 设置输出变量:在部署作业的步骤中,使用
##vso[task.setvariable variable=变量名;isOutput=true]变量值语法定义输出变量,同时给该步骤指定name属性(如示例中的printvar)。 - 跨阶段引用变量:在依赖阶段的
variables块中,通过stageDependencies.源阶段名.部署作业名.outputs['步骤名.变量名']的格式引用输出变量,将其赋值给新的变量。 - 使用变量:在目标作业的步骤中,直接通过
$(变量名)使用承接后的变量。
修正后运行流水线,echo $(myVarfromStage)会正确输出variable,不再出现"echo is off"错误。
内容的提问来源于stack exchange,提问作者David A.Z.
相关产品推荐
相关产品推荐

