While running an azure build pipeline (yml version) is there any programmatic way (inside the pipeline itself) to know if the current pipeline is running on the ms-hosted agent or self-hosted agent?
We have one pre-defined variable called 'Agent.Name' which gives the agent name.
But it keeps changing the agent name (Hosted, Azure) Agent.Name=Hosted, Agent.Name=Azure
Is there any way to determine the type of agent at the pipeline run time.
- task: Bash@3
displayName: Show Agent Name
inputs:
targetType: 'inline'
script: |
echo $(Agent.Name)
No built-in feature to achieve your requirements.
But we can 'for-each' the 'azure pipeline agent pool' to get all of the Microsoft-agent names in it. And then compare.
trigger:
- none
# pool:
# name: VMAS
# 1
stages:
- stage: s1
displayName: get the Microsoft host agents' names
jobs:
- job: testJob
steps:
- task: PowerShell@2
name: setvar
inputs:
targetType: 'inline'
script: |
# logic here. For example you get the vars and put it into this format:
$PAT = "<Your Personal Access Token>"
$org_name = "<Your Organization Name>"
$pool_id = <The microsoft hosted agent pool id>
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic "+$PAT)
$url = "https://dev.azure.com/"+$org_name+"/_apis/distributedtask/pools/"+$pool_id+"/agents?api-version=6.0"
$response = Invoke-RestMethod $url -Method 'GET' -Headers $headers
$response | ConvertTo-Json
$str = "";
foreach ($item in $response.value) {
$str += $item.name
$str += ","
}
Write-Host $str
Write-Host "##vso[task.setvariable variable=outputvars;isOutput=true]$str"
# 2
- stage: s2
displayName: check whether current agent name is one of the above
dependsOn: s1
variables:
vars: $[ stageDependencies.s1.testJob.outputs['setvar.outputvars'] ]
jobs:
- job:
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$varsArr = "$(vars)".Split(',')
$microsofthostagent = 0
foreach ($var in $varsArr)
{
if ($var -eq "$(Agent.Name)")
{
$microsofthostagent = 1
}
else
{
}
}
if( $microsofthostagent -eq 1){
Write-Host "This pipeline is based on Microsoft Host Agent."
}else{
Write-Host "This pipeline is based on Self Host Agent."
}
By default, the self host agent will not have the same name as the Microsoft host agent.
You just need to be careful not to name the self host agent the same as the agent in the Microsoft agent pool (eg "Hosted Agent", "Azure Pipelines ")
On my side, it works:
Microsoft hosted agent
Self hosted agent
As we are using both the ms-hosted & self-hosted so as a solution I started verifying the names of my self-hosted agents (these names are already known to us) & based on this I am able to pick the MS-hosted agents
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.