如何在Azure DevOps Pipeline运行时判断代理类型(托管/自托管)
更可靠的Azure DevOps Agent类型判断方法
替代通过Pipeline名称识别的方案,你可以直接使用Azure DevOps提供的预定义系统变量来判断Agent类型,这是官方支持的可靠方式:
1. 使用Agent.Hosted变量
这是最直接的判断依据:
- 运行在Azure托管代理上时,
Agent.Hosted的值为true - 运行在自托管代理上时,
Agent.Hosted的值为false
YAML Pipeline示例
steps: # Azure托管代理执行的构建步骤 - task: PowerShell@2 displayName: "Azure托管代理专属构建" condition: eq(variables['Agent.Hosted'], 'true') inputs: targetType: 'inline' script: | # 这里写Azure托管环境下的Business Central构建逻辑 Write-Host "Executing build on Azure Hosted Agent" # 自托管代理执行的构建步骤 - task: PowerShell@2 displayName: "自托管代理专属构建" condition: eq(variables['Agent.Hosted'], 'false') inputs: targetType: 'inline' script: | # 这里写自托管环境下的Business Central构建逻辑 Write-Host "Executing build on Self-Hosted Agent"
脚本内直接判断(PowerShell)
if ($env:AGENT_HOSTED -eq "true") { # Azure托管代理逻辑 Write-Host "Running on Azure Hosted Agent - execute cloud-specific build steps" } else { # 自托管代理逻辑 Write-Host "Running on Self-Hosted Agent - execute on-prem specific build steps" }
2. 辅助判断:Agent.PoolName变量
如果需要更精细的区分(比如多个自托管池),可以结合代理池名称判断:
- Azure托管代理的默认池名称为
Azure Pipelines - 自托管代理的池名称是你自行创建的自定义名称(比如
Self-Hosted-BC-Pool)
示例条件:
condition: eq(variables['Agent.PoolName'], 'Azure Pipelines')
为什么原方法不可靠?
通过Pipeline名称前缀判断的方式存在明显缺陷:
- Pipeline名称可被随意修改,一旦命名规则变化,判断逻辑会失效
- 无法区分同一Pipeline在不同代理池的执行场景
内容的提问来源于stack exchange,提问作者Sivaguru Muralidharan
相关产品推荐
相关产品推荐

