Hello!
I’m trying to get the names and environment of all machines of a certain role. Using the API, I expect to be able to query the “machines/all” page and be able to filter by role. An example of the code I’m using is below. I use something very similar to get all the environments then search for a given environment by name to return the Octopus Environment Id.
So what I want to be able to do is return all machines of a given role regardless of what environment they are in. I’m really struggling to find a solution to this current problem, other than query every single environment and see if they have a machine with the role I am interested in. But that seems like an inefficient way to deal with the problem.
Any help truly appreciated.
function Get-OctopusMachines
{
param
(
$apiKey,
$ApiRoot
)
$envUrl = "$apiroot/api/machines/all"
Write-Host $envUrl
write-verbose "machines url: $envUrl"
$macines= Invoke-RestMethod -Uri $envUrl -Method Get -Headers @{"X-Octopus-ApiKey"=$apiKey}
if (!$macines)
{
throw "Octopus Api Helper Exception. Something has gone wrong. Please verify your api root or key."
}
return $machines
}
function Get-OctopusMachinesByRole
{
param
(
$apiKey,
$ApiRoot,
$MachineRole
)
$Machines = Get-OctopusMachines -ApiKey $APIKey -ApiRoot $ApiRoot
$MachineName = $Machines | WHERE { $_.Roles -eq $MachineRole}
if (!$MachineName)
{
throw "Octopus Api Helper Exception. Something has gone wrong. Please verify your Machine Role."
}
write-verbose $MachineName
return $MachineName
}
$OctopusApiKey = "API-BOB"
$OctopusApiRoot = "root"
$OctopusRole = "role"
$splat =
@{
apiKey = $OctopusApiKey
ApiRoot = $OctopusApiRoot
MachineRole = $OctopusRole
}
Get-OctopusMachinesByRole @splat